Search code examples
cfgets

read line with fgets() rewind(File * file) does not work?


char *readLine(int n, char * filename) 
{
FILE * file=fopen(filename,"r");
int i=0;
int BUF=255;
char temp[BUF];
char puffer[BUF];
char* returned_string;
for(i = 0; i < n-1; i++)
if(fgets(temp, BUF, file) == NULL)
    return NULL;

if(fgets(puffer,BUF,file) == NULL)
return NULL;

returned_string = malloc (strlen (puffer) + 1);
strcpy (returned_string, puffer);
rewind(file); 
fclose(file);
return returned_string;
}

calling previous code with :

char * temp=readLine(0,filename);
char * temp2=readLine(1,filename);
char * temp3=readLine(2,filename);

makes all three variables the same although i am trying to read different lines with different content..

I also tried to use rewind(File * file) which should be the same as fseek(file,0,SEEK_SET)

How can I read the lines i want to read?

Thank you in advance!


Solution

  • Whether you call the function with n as 0 or 1, you're going to get the first line in the file. If n is 0 or 1 and i is 0, then i is not less than n - 1, so your for loop will never execute.

    The function should, however, correctly return the second line when called with n as 2. It works for me:

    Input file:

    Test line 1
    Test line 2
    Test line 3
    Test line 4
    Test line 5
    

    Calls:

    int main (void) {
    
        char *str0, *str1, *str2;
    
        str0 = readLine (0, "test");
        str1 = readLine (1, "test");
        str2 = readLine (2, "test");
    
        printf ("%s%s%s\n", str0, str1, str2);
    
    return 0;
    
    }
    

    Output:

    Test line 1
    Test line 1
    Test line 2
    

    So if it isn't working for you, I suspect some corruption in your input file; or the first two lines of the file are the same.

    Also, rewind(file) is redundant in your code.