How to find if string exists in file?

Game Editor comments and discussion.

How to find if string exists in file?

Postby jimmynewguy » Wed Dec 12, 2012 4:37 am

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);
}
Working on a probably too ambitious project! Wild-west-adventure-RPG-shooter-thing.
User avatar
jimmynewguy
 
Posts: 1137
Joined: Sat Mar 31, 2007 6:27 pm
Score: 89 Give a positive score

Re: How to find if string exists in file?

Postby skydereign » Wed Dec 12, 2012 8:35 am

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.
User avatar
skydereign
 
Posts: 3510
Joined: Mon Jul 28, 2008 8:29 am
Score: 589 Give a positive score

Re: How to find if string exists in file?

Postby jimmynewguy » Wed Dec 12, 2012 4:10 pm

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!
Working on a probably too ambitious project! Wild-west-adventure-RPG-shooter-thing.
User avatar
jimmynewguy
 
Posts: 1137
Joined: Sat Mar 31, 2007 6:27 pm
Score: 89 Give a positive score


Return to GE - General

Who is online

Users browsing this forum: No registered users and 1 guest