arrays - Reading a file line by line in C -


I'm trying to write some code that opens a file, read its content line from line and from among these lines Store each array with an array.

First of all I open the file and count the number of lines, each row is of a certain length, so I just do this:

  char buf2 [ line length]; Int in2 = open ("toSend2", O_RDONLY); Int number_of_lines = 0; For (;;) {char * p2 = buf2; Int count = read (in2, p2, LINE_LENGTH); If (count> <0) {printf ("ERROR"); break; } Break (calculated == 0); NUMBER_OF_LINES ++; Printf ("Count:% d \ n", Count); Printf ("file2 row:% s", p2); Printf ("\ n"); } Off (in2);  

So far, it works well, number_of_lines is actually the number of rows in the "toend2" file and each of my printf lines are contained in that file.

Now with the number of lines, I create an array of stars and then basically go back to the whole file, but at this time, I would like to store every line in the array (possibly A better way to figure out is the number of rows in a file, but whatever I tried it failed!)

  char * array [number_of_lines]; Int b = 0; Int 3 = 0; In3 = open ("toSend2", O_RDONLY); For (;;) {char * p3 = buf3; Int count = read (in2, p3, LINE_LENGTH); If (count & lt; 0) {printf ("ERRORRRR"); break; } Break (calculated == 0); Array [b] = p3; B ++; Printf ("Count:% d \ n", Count); Printf ("FILE 2 LINEEEEEE:% s", P3); Printf ("\ n"); } Off (in3);  

This, of course, does not work: the last line and last line of each of my printf files is, for example, the first printf will be:

FILE 2 LINEEEEEEE: "The first line of the file" "the last line of the file"

And for the loop after that, when I find out the contents of my array, then I think the last line of every object bus file That's because it's the same pointer in the array all the time (towards that moment) Points to a different line) I put each time, but in the end it will point to the last line, so everything will be the last row.

How would I solve my problem?

ps: I have just started, so please assume I know the basic things about it too: (

  • Use stdio, i.e. fopen () , fgets () and to I / O For fclose () you are using very low-level Pausx-style I / O for any good reason.
  • You are assigned dynamically each new line To do this, you can use strdup ()
  • Remember that things can be wrong; files may fail to open, lines may fail, read, and fail to allocate memory. Work accordingly.

Comments

Popular posts from this blog

Is there an open source WebSockets (JavaScript) XMPP library? -

java - Is there an object like a "Set" that can contain only unique string values, but also contain a count on the number of occurrences of the string value? -

iphone - How do I make a UIPickerView in a UIActionSheet -