2015-02-15 5 views
-2

Я пытаюсь выполнить это упражнение: С помощью fscanf()10 и fprintf() функции выполняют программу, которая записывает некоторые числа, полученные от ввода в файле, считывает значения один за другим, печатает значения увеличиваются на единицу и переписывают их в файле.Проблемы с записью и чтением из файла

Вот что я сделал:

include <stdio.h> 
#include <cstdlib> 

int main() 
{ 
    FILE *fp_1, *fp_2; 
    int n, num, num_inc, i; 

    fp_1 = fopen("output.txt", "w"); 
    if (fp_1 == NULL) { 
     printf("Error"); 
     return 1; 
    } 
    printf("How many values you want to write? "); 
    scanf("%i", &n); 
    for(i=0; i<n; i++) { 
     printf("Write the %i number: ", i+1); 
     scanf("%i", &num); 
     fprintf(fp_1, " %i ", num); 
    } 
    printf("Values read from file:\n"); 
    fp_2 = fopen("output.txt", "r"); 
    if(fp_2 == NULL) { 
     printf("Error"); 
     return 2; 
    } 
    i = 0; 
    while(!feof(fp_2) && i<n) { 
     fscanf(fp_2, " %i ", &num); 
     num_inc = num+1; 
     fprintf(fp_1, " %i ", num_inc); 
     printf("%i value read is: %i\n", i+1, num_inc); 
     i++; 
    } 

    fclose(fp_1); 
    fclose(fp_2); 
    system("pause"); 
} 

Вот результат:

How many values you want to write? 5 
Write the 1 number: 32 
Write the 2 number: 124 
Write the 3 number: 55646 
Write the 4 number: 32 
Write the 5 number: 112 

Values read from file: 

1 value read is: 113. 

Проблема заключается в том, что есть только один считанное значение.

Спасибо!

+2

cstdlib говорит, что вы используете компилятор C++. Удалите это и используйте компилятор C. –

ответ

0

Ключ должен использовать другой файл для второго выхода.

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    FILE *input_file, *output_file; 
    int n, num, num_inc, i; 

    input_file = fopen("input.txt", "w+"); // Actually it is the input for the next step. 
    if (input_file == NULL) { 
     printf("Error"); 
     return 1; 
    } 
    printf("How many values you want to write? "); 
    scanf("%i", &n); 
    for (i = 0; i < n; i++) { 
     printf("Write the %i number: ", i + 1); 
     scanf("%i", &num); 
     fprintf(input_file, " %i ", num); 
    } 

    rewind(input_file); // Rewind to the beginning to perform reading. 

    output_file = fopen("output.txt", "w"); // The name of the output file (must be different from the input one). 
    if (output_file == NULL) { 
     printf("Error"); 
     return 2; 
    } 

    printf("Values read from file:\n"); 
    i = 0; 
    while (!feof(output_file) && i < n) { 
     fscanf(input_file, " %i ", &num); 
     num_inc = num + 1; 
     fprintf(output_file, " %i ", num_inc); 
     printf("%i value read is: %i\n", i+1, num_inc); 
     i++; 
    } 

    fclose(input_file); 
    fclose(output_file); 
    system("pause"); 
} 
+0

Спасибо! :) –

1

Попробуйте сделать fclose на fp_1 перед тем, как открыть файл снова как fp_2.

+0

Другие ошибки ...:/ –

Смежные вопросы