scuzz1
asked on
Problem with fscanf
Hi,
I am having a problem with fscanf. The program is reading in small text files and altering the data slightly and writing out to another file. It works good, until it hits a file the has tabs in the first line. It reads up to the tab as line1 and then after the tab as line2. My question is how can I get fscanf to read the entire line1 as line1. Does fscanf have a problem with tabs?
Jim
I am having a problem with fscanf. The program is reading in small text files and altering the data slightly and writing out to another file. It works good, until it hits a file the has tabs in the first line. It reads up to the tab as line1 and then after the tab as line2. My question is how can I get fscanf to read the entire line1 as line1. Does fscanf have a problem with tabs?
Jim
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I thought that was the way to go. I just did not want to redo what I had. I was hoping that there was something that I could do that would let me keep fscanf in the program. This is a small one time do the deed and trash executable so I was looking for quick and easy. The %[^\n] option you wrote did not work so I guess fgets is the answer.
Thanks for your help,
Jim
Thanks for your help,
Jim
>> The %[^\n] option you wrote did not work so I guess fgets is the answer.
It should if used correctly ;) Can you show how you used it ?
It should if used correctly ;) Can you show how you used it ?
ASKER
fscanf (stream, "%[^\n]", char_array);
>> fscanf (stream, "%[^\n]", char_array);
That's ok. I assume your problem is that the next fscanf does not behave correctly ? If so, then that's because the \n is still on the stream and is read first by the next fscanf.
So :
fscanf (stream, "%[^\n]\n", char_array);
would skip that \n.
But again : fgets is a much better alternative.
That's ok. I assume your problem is that the next fscanf does not behave correctly ? If so, then that's because the \n is still on the stream and is read first by the next fscanf.
So :
fscanf (stream, "%[^\n]\n", char_array);
would skip that \n.
But again : fgets is a much better alternative.
ASKER
I got a bunch of null chars in the arrays when I tried that fscanf thing. Like I said, I was just hoping. It would have worked with fscanf if it were just a few files that were messed up. It seems as though there are more than I thought. I will just go with the fgets.
Thanks Again.
Jim
Thanks Again.
Jim
format string should match the input.
You would be better off reading in a string and parsing it
while (fgets(buffer, MAX_LINE_LEN, file_ptr))
{
char * temp = strtok (buffer, "\t"); //tab delimited file
while (temp)
{
//process value pointed to by temp .. use strtol, strtod etc as suitable
temp = strtok (NULL, "\t");
}
}