Page 1 of 1

How to find if string exists in file?

PostPosted: Wed Dec 12, 2012 4:37 am
by jimmynewguy
I am trying to find a way to check if a string already exists in a text file. If the string does not exist, then I want to append it to the file. This code I made does not work, can anyone help?

Code: Select all
char MapName[256] = "Name";
char line[256];
int found = 0;
FILE * levs = fopen("levels.text", "r");
while(fgets(line, 255, levs)) {
if(strcmp(line, MapName) == 0) {
found = 1;
}
}
fclose(levs);

if(!found) {
FILE * GO = fopen("levels.txt", "a+");
fprintf(GO, "%s\n", MapName);
fclose(GO);
}

Re: How to find if string exists in file?

PostPosted: Wed Dec 12, 2012 8:35 am
by skydereign
Is there a certain format to the file? For instance one word per line? I assume so by your code, which means the problem you are having is that fgets does not remove the newline character. So you can either add the newline to your MapName string, or remove it from the line string.

Re: How to find if string exists in file?

PostPosted: Wed Dec 12, 2012 4:10 pm
by jimmynewguy
It just saves each MapName line by line so it would contain:

This is Map 1
Jungle Map
The Next Map
ect.

I tried adding the new line character, like this, but it did not work.
Code: Select all
sprintf(test, "%s\n", MapName);
if(strcmp(line, test) == 0)


EDIT: I read each line and stored them into an array, then looped through the array and checked it with MapName and it works now. Thanks for your help!