Problems with fseek () and reading from a file

I started learning C (via Youtube and K & R) a while ago, and I'm trying to write some programs as a practice. Currently, I want to create a program that reads words from a file and compares the beginning with the input from the user. The program successfully compares the first word and gives me the result, but I just can not get fseek () to move correctly to the next line! (This is the current version of the part that searches 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 srtFile string, but this is not very good. I even tried to configure fseek () manually, but it just didn't move. Words from my file: First, Last, Index, Field, ID, Number, Fire, Film. (each is on a new line). When I run the program and type F (to search for a word that has 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'm desperate. Any ideas / hints?

[EDIT] Many thanks to everyone who helped me with this!

+6
source share
2 answers

The problem is due to the fseek SEEK_CUR parameter.

You move the cursor twice .

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

The solution might be to completely remove the fseek call.

Another solution is to use SEEK_SET instead of SEEK_CUR, but with a counter that contains the total number of characters read (including a 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 the file.

SEEK_CUR moves the cursor from the current position.

+3
source

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 file size (offset) . So he skipped Last and read Index as line 2.

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

+2
source

Source: https://habr.com/ru/post/986071/


All Articles