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!
fileCount
? If you're in Windows, you might want to open with "rb" because of the CRLF convention. If you're reading through the file sequentially, why bother withfseek
at all? – Interfluentfseek
may be dangerous for files opened in text mode; explained here. Summary: because of\n
<->\r\n
conversion, the parameter tofseek
should either be 0 or come from an earlierftell
call. So you should use bothfseek
andftell
in your program (or none? Maybe you don't needfseek
at all?). – Clayton