I have a file with multiple lines. Each line has two numbers separated by a white-space. I need to use this code, which prints the first line, to print the whole file, but doing it line by line
do
{
fscanf(fp,"%c", &c);
if(c == ' ')
break;
printf("%c", c);
}
while (c != ' ');
do
{
fscanf(fp, "%c", &c);
printf("%c", c);
}
while( c != '\n');
I tried to use fgets but got into an infinite loop.
while(fgets(buf, sizeof buf, fp) != NULL) // assuming buf can handle the line lenght
{
//code above
}
Why i cant use fgets like that to print it line by line?
Sample
Input:
10 5003
20 320
4003 200
Output
10 5003
20 320
4003 200
If we replace printf(fp, "%c", c) with printf("%c", c) (because we are not printing in a file, right?), the following sample should do the job (it creates test file with ten lines).
Obviously I can't use your exact code, or you would not have asked the question, but this is a similar idea, done a bit differently, and also using the
fgets
which was causing you trouble. It works by searching each line for digits, and non-digits. Note that I have#define MAXLEN 2000
to be generous, because in the previous question, you say each number can have 500 digits, so the line might be at least 1000 characters.EDIT you could make it more concise like this, with a loop to read each set of digits:
Program output (from your input):