views:

676

answers:

6

hi, 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!

+1  A: 

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.

Randolpho
C is case sensitive, so those all need to be in lower case.
Jerry Coffin
A: 

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...

dionadar
+1  A: 

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.

ty
A: 

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 (e.g. 4 megabytes) of data at a time.

Jerry Coffin
I have my program perfectly working in C#, and I am very new to C. What I am doing is getting an ascii file consisting of 3 million files, which every line consists of three floating points separated by space... And I have another file which is approximately of the same size. They are running in outer and inner loops, so it is in total 3million*3million,....
asel
@asel: and what are you doing with that cross-product?
Jerry Coffin
A: 

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
}
sevity
You seem to have a mistake. You declare a `string line` but then call `getline(input, s)`. Perhaps `s == line` ?
Chris Lutz
yes. I fixed it. thanks.
sevity
A: 

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.

Greg Bacon