简体   繁体   中英

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!

UPDATE

try this code instead it goes to the nth line and returns it (I believe that this is what you want to do) fseek goes to the line before and fgets gets the line that follows (meaning the targeted line) :

char *readLine(int n, char * filename) 
{
FILE * file=fopen(filename,"r");
int i=0;
int BUF=255;
char puffer[BUF];
char* returned_string;
fseek(file , n-1 ,SEEK_SET);
if(fgets(puffer,BUF,file) == NULL)
    return NULL;
returned_string = malloc(sizeof(puff));
strcpy (returned_string, puffer);
fclose(file);
return returned_string;
}

in malloc use malloc(sizeof(puff)) or malloc(BUFF) for it is much faster because when you use malloc(strlen(puff) + 1) the compiler has to calculate strlen(puff) every time

The entire rewind is a red herring (a deliberate obfuscation). It seems to me the only problem is that your main "skip line" loop is not correct. Try this in the for..loop instead:

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

Since you want to read line n , you have to skip lines 0..n-1 . Your for-loop ended one line too early.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM