Bjørn Augestad said:
Richard said:
Bj[o]rn Augestad wrote:
Richard Heathfield wrote: <all snipped>
Allan Bruce wrote:
Hi there,
I am reading a file into a char array, and I want to find if a string
exists in a given line.
I cant use strcmp since the line ends with '\n' and not '\0'.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Is there a
similar function that will do this, or will I have to write my own?
Maybe he can ignore the \n and just use strstr() instead? He won't get
exact matches for the whole line, but he will "find if a string exists
in a given line". ;-)
Well, he did say quite clearly that there was no '\0' at the end of the
data. Or did I misunderstand him?
I don't know.
I was just assuming(I know, I know...) that the OP was reading a file
line by line using fgets() and then tried to match some string with the
line read, but ran into problems because of the trailing \n.
Only time and some source code will tell. ;-)
I am using this to read the file:
// find how big the file is
fseek(fptr, 0, SEEK_END);
size = ftell(fptr);
//allocate memory for string
if ( (contents = new char[size]) == NULL)
return 0;
Basically reading it in one big chunk, since I am doing some things to the
code that take a long time so I wanted to keep the file open for as little
time as possible.
I use strstr() to find some matches and also use strcmp() to see if some are
true for example, a line may be:
# Material: Porsche_Body
Now this will be stored with a '\n' at the end but no '\0'.
In this example I wish to search for "Material:" using strstr() but if it
doesnt exist then strstr() is causing undefined behaviour. If strstr() is
successful, then I want to see if the material name matches what I already
have loaded using strcmp() but since the '\0' isnt there - problems. I
count how many chars until the '\n' and then use strncmp I suppose, but that
doesnt get around the strstr() and I want to know for future how to use
strcmp with '\n' terminator.
From the gist of it, I should program my own function, or better still
macro.
Am I correct?
Thanks
Allan