Fosh Fosh - 11 days ago 5
C Question

Reading strings from file

Ok so, I have the following bit of code in a program I'm making

names.txt contains the following:

PersonA.txt
PersonB.txt
PersonC.txt


then, In order to store them into an array here's what I'm doing:

FILE* fnames;

fnames=fopen("names.txt","r");

nlines=file_lines(fnames); // function I made to calculate lines (working)

f_array[nlines][29]; // 29 just a ramdom number for the length of person


for(i=0; i < nlines; i++)

{

fgets(f_array[i], 29, fnames);

printf("file name: %s\n", f_array[i];

}


However the output is just rubish like

file name: random letters squares and question marks

file name: (same)

file name: (same)


I'm not finding the reason for this to happen as the other similar fgets I have
is working just fine.

Answer

Because in the function file_lines, you had iterated through the file to calculate the number of lines, the FILE* now point to the position at the end of file.

You need to rewind of fseek to the begin of file to read again.

Place one of those 2 lines before the for loop, or better, at the end of file_lines function:

fseek(fnames, 0, SEEK_SET); // same as rewind()
rewind(fnames);             // same as fseek(fp, 0, SEEK_SET)

If your program has read the file before calling the function file_lines, You need to call this function at the very begin of file_lines

long original_offset = ftell(fnames);

then call this function at the very end of file_names

fseek(fnames, original_offset, SEEK_SET);

Alternatively, you can read the filename while you iterate the first time.