0

given a file (file.txt) with the following content:

123 456
789 101

I don't understand why after that I read from the file the first line (by fscanf) it's not work to read the second line.

int main() {
    FILE* fp = fopen("file.txt", "r");
    if (fp == NULL)
        return 1;
    int n1, n2;
    fscanf(fp, "%d %d", &n1, &n2);
    char buffer[10]="";
    fgets(buffer, 10, fp);
    printf("%s", buffer);
}  

What is the problem? (I tried to add \n in the format of fscanf and then it's works, but I don't understand why I must add \n to the format of fscanf?)

J.Roe
  • 73
  • 1
  • 8
  • 1
    You basically can't intermix `fscanf` and `fgets` like this. It never works – Steve Summit Mar 11 '18 at 13:56
  • Either call `fgets` plus `sscanf` to read the first line, or use `fscanf` with `%s` or `%[^\n]` to read the second one. – Steve Summit Mar 11 '18 at 13:57
  • "why I must add \n to the format of fscanf" you don't have to, but it is one way to cope with ill advised mix of using `fgets()` and `fscanf()`. Recommend to use only one of those 2. – chux - Reinstate Monica Mar 11 '18 at 13:57
  • @SteveSummit Why not? if I will wirte `fscanf(fp, "%d %d\n", &n1, &n2);` it's will be correct. – J.Roe Mar 11 '18 at 13:58
  • @J.Roe `fscanf(fp, "%d %d\n"...` is not correct if the line after `123 456` is only white-space. It is consumed by `fscanf(fp, "%d %d\n"...` – chux - Reinstate Monica Mar 11 '18 at 13:59
  • 1
    @J.Roe I was exaggerating slightly when I said it "never" works, but it remains a magnificently error-prone way of doing things. As I said, I recommend not trying to intermix `*scanf` and `*gets`. If you want to understand why adding `\n` to the format string seemed to fix it, see one of the several thousand related questions. *Everybody* has this problem when they try to call `*gets` after `*scanf`. – Steve Summit Mar 11 '18 at 14:01
  • @J.Roe Do not mix the use of `fgets()`, `fscanf()` until you know why code _should not mix_ them. By that time one will understand how to use them properly together. For know, consider never using `scanf()`, `fscanf()`. `sscanf()` is OK. – chux - Reinstate Monica Mar 11 '18 at 14:02
  • @SteveSummit ok, thank you anyway. – J.Roe Mar 11 '18 at 14:03

0 Answers0