I have the following C# code snippet
string[] lines = File.ReadAllLines(@"C:\test.txt");
for(int i=0; i<lines.Length; i++)
Console.WriteLine(lines[i]);
Can you help me to convert it to C?
Thanks!
If you plan to use Ansi Standard C, you'll need fopen
, fgets
, and printf
to do what you want.
the process should work pretty much as expected:
Open the file, figure out the encoding (ReadAllLines does that for you) read the input with the guessed encoding, recode it into your target format - which will probably be UTF16 - and print it to stdout...
Just for what it's worth, if you're just copying the data from one stream to another, there's no need to worry about doing it line by line -- the lines are determined by new-line characters (or carriage returns and/or carriage return/line feed combos) in the data.
If you simply copy the data through without changing it, the lines will be preserved. To maximize speed, you probably want to open the file in binary mode, and use fread/fwrite to copy fairly large chunks (eg 4 megabytes) of data at a time.
you can do it in simple way with C++.
ifstream input("test.in");
string line;
while(getline(input, line)) {
//Your code for the current line
}
Using fgets
invites tricky edge cases:
On my blog, I posted an example of how to do it robustly with fgets
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.