简体   繁体   中英

c reading a text file into array line by line and print them

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.

Here's a tutorial that does almost exactly what you want .

Take a look at the fopen and fgets functions.

fgets in particular will read until a newline character is reached, so it is perfect for reading in text files a line at a time.

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:

  • What if a line's length is greater than the size of a fixed-width buffer?
  • What if the file doesn't end with a newline?
  • What if the last line fits exactly in the buffer without causing the end-of-file status to be set?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM