Thursday 15 August 2013

Reading lines from c file and putting the strings into an array -



Reading lines from c file and putting the strings into an array -

i'm trying add together each line of c file array. contents of files.txt is

first.c second.c third.c fourth.c

i want code print each of these lines, add together line array, , print out each entry in array. right doing first part correctly adding fourth.c array. can tell me wrong code?

#include <stdio.h> #include <stdlib.h> int main(void) { int i=0; int numprogs=0; char* programs[50]; char line[50]; file *file; file = fopen("files.txt", "r"); while(fgets(line, sizeof line, file)!=null) { //check sure reading correctly printf("%s", line); //add each filename array of programs programs[i]=line; i++; //count number of programs in file numprogs++; } //check sure going array correctly (int j=0 ; j<numprogs+1; j++) { printf("\n%s", programs[j]); } fclose(file); homecoming 0; }

you need alter

programs[i]=line;

to

programs[i]=strdup(line);

otherwise pointers in programs array point same location (that line).

btw: if files.txt contains more 50 lines, run trouble.

c arrays file-io

No comments:

Post a Comment