Чтение и запись с использованием fscanf и fprintf в цикле while - PullRequest
0 голосов
/ 20 ноября 2018

РЕДАКТИРОВАТЬ: С помощью членов здесь я обновил свой код. В настоящее время я пытаюсь решить, почему цикл while никогда не обнаруживает EOF.

Мне не нужен счетчик приращений для [i] в ​​моей функции returnStats (). Я нашел это интересным, и я не могу понять, почему.

В частности, в цикле while, который сканирует до конца файла. Как программа узнает, что нужно перейти к следующему элементу массива?

Кроме того, поскольку я больше не счетчик, я не могу использовать его, чтобы вести счет, поэтому я использовал j вместе с j ++.

Детали моей программы:

#include <stdio.h>

// function prototypes
void loadTextFile();
void returnStats();

// begin main function
int main(void){

    loadTextFile();
    returnStats();

    return 0;
} // end main function

// function which returns the number of entries, average, and maximum of the numbers read
void returnStats(){

    FILE *file = fopen("question5.txt","r");

    if(file == NULL)
    {
        printf("question3.dat cannot be opened!\n");
        fprintf(stderr, "Error opening the fil!\n");
    }

    else
        printf("\nquestion3.dat was opened successfully for reading.\n\n");

    int i=0, j=0; 
    int numbers[4];
    float average=0.0;
    int max=0;

    while(fscanf(file, "%d", &numbers[i]) != EOF) 
    {
        printf("%d was read from .txt file\n", numbers[i]);
        average += numbers[i];  

        if(numbers[i]>max)
            max = numbers[i];

        j++;    

    }   

    printf("\nThe number of entries is: %d", j);    
    printf("\nThe average of the numbers is: %.2f", average/4);
    printf("\nThe maximum of the numbers is: %d", max);

    fclose(file);

} // end returnAverage


// function to load the .txt file with array values so we may execute main on any computer. 
void loadTextFile(){

    FILE *file = fopen("question5.txt","w");

    if(file == NULL)
    {
        printf("question3.dat cannot be opened!\n");
        fprintf(stderr, "Error opening the fil!\n");
    }

    else
        printf("question3.dat was opened successfully for writing.\n");

    int numberArray[4]={56, 23, 89, 30};

    int i=0;

    for(i=0;i<4;i++)
    {
        fprintf(file, "%d\n", numberArray[i]);

    }

    printf("\nThe data was successfully written\n");

    fclose(file);
} // end function loadTextFile

Код доработки

#include <stdio.h>

// function prototypes
void loadTextFile(FILE *file);
void returnStats(FILE *file);

// begin main function
int main(void){

    FILE *text = fopen("question6.txt","w");

    if(text == NULL)
    {
        printf("question6.dat cannot be opened!\n");
        fprintf(stderr, "Error opening the fil!\n");
    }

    else
        printf("\nquestion6.dat was opened successfully for Writing.\n\n");

    loadTextFile(text);
    returnStats(text);

    fclose(text);

    return 0;
} // end main function

// function which returns the number of entries, average, and maximum of the numbers read
void returnStats(FILE *file){


    int i=0;
    int number[4];

    while(fscanf(file, "%d", &number[i]) != EOF)
    //for (i=0;i<4;i++)
    {   
    //  fscanf(file, "%d", &number[i]);
        printf("\n%d : Was Read from the File\n", number[i]);
        fprintf(file, "%d\n", number[i]+10);
    }

} // end returnStats

// function to load the .txt file with array values so we may execute main on any computer. 
void loadTextFile(FILE *file){


    int numberArray[4]={56, 23, 89, 30};

    int i=0;

    for(i=0;i<4;i++)
    {
        fprintf(file, "%d\n", numberArray[i]);
        printf("\n%d : was written to the file\n", numberArray[i]);

    }

    printf("\nThe data was successfully written\n");

} // end function loadTextFile

Ответы [ 2 ]

0 голосов
/ 21 ноября 2018

Простое решение, если это не вредит, - это добавить некоторую строку в конце вывода в дочернем / клиентском процессе, например «\ nend of output \ n».Я не уверен, что fflush () может помочь или просто попробовать

0 голосов
/ 20 ноября 2018

вам не нужно увеличивать позицию, потому что для этого вам не нужен массив.Ваша программа использует только первый элемент массива.Таким образом, он заменяет старое значение новым файлом.Но у вас есть только последнее значение в памяти.

...