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
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.
#include <stdio.h>
#include <ctype.h>
#define MAXLEN 2000
int main(void)
{
FILE *fp;
char line[MAXLEN];
char *ptr;
if((fp = fopen("test.txt", "rt")) == NULL)
return 0; // or other action
while(fgets(line, MAXLEN, fp) != NULL) {
ptr = line;
// first number
while(*ptr && !isdigit(*ptr)) { // skip non-digits
ptr++;
}
while(*ptr && isdigit(*ptr)) {
printf("%c", *ptr++); // print digits
}
printf(" ");
// second number
while(*ptr && !isdigit(*ptr)) { // skip non-digits
ptr++;
}
while(*ptr && isdigit(*ptr)) {
printf("%c", *ptr++); // print digits
}
printf("\n");
}
fclose(fp);
return 0;
}
EDIT you could make it more concise like this, with a loop to read each set of digits:
char *terminate = " \n"; // 1st number ends with space, 2nd with newline
int i;
while(fgets(line, MAXLEN, fp) != NULL) {
ptr = line;
for(i=0; i<2; i++) {
while(*ptr && !isdigit(*ptr)) { // skip non-digits
ptr++;
}
while(*ptr && isdigit(*ptr)) {
printf("%c", *ptr++); // print digits
}
printf("%c", terminate[i]); // space or newline
}
}
Program output (from your input):
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).
#include <stdio.h>
#include <stdlib.h>
int main() {
char c;
FILE* fp;
fp = fopen("test.txt", "w+");
for (int i = 0; i < 10; i++)
{
fprintf(fp, "Test line %i\n", i);
}
rewind(fp);
do {
do {
fscanf(fp, "%c", &c);
if (c == ' ')
break;
printf("%c", c);
} while (c != ' ');
do {
fscanf(fp, "%c", &c);
printf("%c", c);
} while (c != '\n');
}while ((c=fgetc(fp))!=EOF?printf("%c", c):0);
fclose(fp);
}