Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Troubles with fseek() and reading from file

Tags:

c

fgets

fseek

I have started learning C (via Youtube and K&R) some time ago and I am trying to write some programs as practice. Currently I want to create a program that reads words from a file and compares the beginning of it with the input from the user. The program successfully compares the first word and gives me a result, but I just can't get the fseek() to move correctly to the next line! (This is the current version of the part that seeks for words.)

fp= fopen("final.txt", "r");
for (i=0; i<8; i++){

    fseek(fp, fileCount, SEEK_CUR);

    fgets(strFile, 20, fp);

    fileCount= strlen(strFile);

    printf("Strlen %d. is: %d\n", i+1, fileCount);
    printf("String is %s", strFile);

    compareStr(strUser, strFile);
};

fclose(fp);

fileCount is set to 0 and strlen() should return the length of the string srtFile, but it doesn't quite well. I even tried setting fseek() manually, but it just wouldn't move. The words from my file are: First, Last, Index, Field, ID, Number, Fire, Film. (each is in a new line). When I run the program and type in F (to search for a word that has a capital f), the output is :

Type in the letters: F
Strlen 1. is: 6
String is First
Match found: First

Strlen 2. is: 6
String is Index
Strlen 3. is: 1
String is
Strlen 4. is: 2
String is D
Strlen 5. is: 5
String is mber
Strlen 6. is: 1
String is
Strlen 7. is: 3
String is ilmStrlen 8. is: 3
String is ilm
Process returned 0 (0x0)   execution time : 2.218 s
Press any key to continue.

I am desperate. Any ideas/clues?

[EDIT] A big thank to everyone who helped me with this!

like image 458
Milan Todorovic Avatar asked Apr 27 '15 15:04

Milan Todorovic


2 Answers

The issue here appears because of the fseek SEEK_CUR parameter.

You are moving the cursor twice.

One move is done by fgets (it reads and then moves the cursor forward). And the second move is done manually by fseek.

A solution may be to completely remove the fseek call.

Another solution is to use SEEK_SET instead of SEEK_CUR, but with a counter that holds the total number of character read (including new line character). For this solution to work you also need to change

fileCount= strlen(strFile);

to

fileCount += strlen(strFile) + 1;

SEEK_SET moves the cursor from the beginning of file.

SEEK_CUR moves the cursor from the current position.

like image 199
Serendipity Avatar answered Oct 01 '22 04:10

Serendipity


Your problem is that you are not using fseek() correctly.

In your code,

fseek(fp, fileCount, SEEK_CUR);

sets the pointer to where its current at plus the filecount(the offset). That's why it skipped Last and reads Index as string 2.

To fix this, simply remove the fseek() statement.

like image 20
Thomas Hsieh Avatar answered Oct 01 '22 03:10

Thomas Hsieh