LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   fscanf with optional fields, spaces? (https://www.linuxquestions.org/questions/programming-9/fscanf-with-optional-fields-spaces-519944/)

phyx 01-16-2007 04:50 PM

fscanf with optional fields, spaces?
 
I'm trying to read a file into and create a single long string based on the contents of the file. However, it has to accommodate for different amounts of spaces, commas, quotes, and end of lines.

Input file input.txt:
,abc hi
"def hi(1)"
ghi bye bye(3)
jkl hello,
mno cat, "pqr dog mouse(4)", stu bird snake
vwx
fish

Output Final string
"abc hi, def hi(1), ghi bye bye(3), jkl hello, mno cat, pqr dog mouse(4), stu bird snake, vwx fish"

Here's what I've tried:
char string[40];
char string2[40];
char junk[20];
char junk2[20];
int count = 0;
char strFinal[200];
FILE *fin;

fin = fopen("input.txt", "r");

if (!fin)
return -1;

while (fscanf(fin, "%[^, ()\t]%[, \t]%[^, \t]%[, \t]", &string, &junk, &string2, &junk2))
{
if (count++ > 1)
{
strcat(strFinal, ", ");
}

strcat(strFinal, string);
strcat(strFinal, " ");
strcat(strFinal, string2);
}

...

// strip " from strFinal, print final string

theNbomr 01-26-2007 05:16 PM

Hope this isn't too late...
It seems to me that you will just drive yourself crazy trying to use fscanf() to cover all of the possible permutations. If you should think more in terms of how you want to modify the newline-delimited data as a whole, and then read it as complete lines. You can modify it according to your requirements using the large family of standard C library functions for handling strings, including a final strcat(), as you are doing now.
It looks like you simply want to remove any leading comma, strip all double-quotes, and append a comma unless it is the last string to concatenate to the output. Finally, enclose the result in double quotes. Looking at the problem this way is a step toward thinking in terms of regular expressions, which leads me to my final point:
Really, if this is the whole job for your program, I suggest you consider Perl as your language. These things can be done in about 5 or 6 lines, or even on the commandline in Perl.
--- rod.


All times are GMT -5. The time now is 07:04 AM.