Hello. There was a problem when working with files, I provide the code:

#define _CRT_SECURE_NO_WARNINGS #include "stdafx.h" #include "stdio.h" #include "stdlib.h" int main() { int a, b; FILE *fp; FILE *fp2; if ((fp = fopen("input", "r")) != NULL) { fscanf(fp, "%d %d\n", &a, &b); printf("yes.\n"); } else { printf("no"); } fclose(fp); fp2 = fopen("output", "w"); fprintf(fp2, "%d %d\n", a, b); fclose(fp2); exit(1); return 0; } 

I will describe the situation. There are 2 files: input and output. The first one contains several lines in each of which there are two numbers, separated by a space, say as in the example below: 5 6 7 15 9 568 23 75

The task to output to the output file is the same as in input, but when compiling the code above, only the first line is output to output, i.e. 5 6 and the rest not. What to add or remove in the code to solve the problem? Thank.

  • The cycle must be added - Vladimir Martyanov
  • one
    Your code does exactly what it should: reads two numbers from the first file (5 6) and writes them to the second. As you wrote it, so it works. - PinkTux
  • While loop It is possible here in more detail ... - Vyacheslav161
  • Read more about the cycles in the textbooks. - Vladimir Martyanov
  • Well, I understood - Vyacheslav161

2 answers 2

The fact is that you read from the input only the first two characters. The best way to use the getc () or getchar () function in your case is enough for your task. Well, the cycle of course. Something like:

 while ((ch = getc (input)) != EOF) { putc (ch, output); } 
  • one
    Add int ch; before the code example. Otherwise, the vehicle decides that once we read character by character, then char ch; will be right (and wrong) - avp
  • ch is actually char! This is why functions getc & putc are used. - Andrej Levkovitch
  • Read (only carefully) man getchar and be sure to think about how to read any character , and EOF will be different from them? Or maybe it would be better if you try to implement some part of libio yourself (FILE * I / O, part of which is getc & putc mentioned by you) - avp
  • EOF usually returns -1, which is quite within the char range. All characters found in the file — a priori will be read by function, and when the end of the file is reached — it will be returned to EOF. What could be the problem? - Andrej Levkovitch
  • @AndrejLevkovitch, according to the standard char can be either signed or unsigned - Pavel
 int a, b; FILE *fp; FILE *fp2; if (((fp = fopen("input", "r")) != NULL) && ((fp2 = fopen("output", "r")) != NULL)) { while (fscanf(fp, "%d %d\n", &a, &b) == 2) fprintf(fp2,"%d %d\n",a,b); fclose(fp); fclose(fp2); } 
  • And if in line there will be only one number? - avp
  • If fp opens, and fp2 does not, then who will close fp ? - PinkTux
  • The line assumes the presence of exactly two numbers - Vyacheslav161