简体   繁体   中英

Writing a sequence of numbers to a file in C

I am new to programming. I have written a program that performs a certain operation with numbers, all I need to do now is to read those numbers from a file and to write them into a different file. I am using this code: char number[20]; int value, choice, result;

{
    FILE *file_in;
    file_in = fopen("roman.txt", "r");


    while (!feof(file_in))
    {
        fscanf(file_in, "%s", number);
        fclose(file_in);
        FILE *file_out;

        result = RomantoArabic(number, value);

        file_out = fopen("arabic.txt", "a");
        fprintf(file_out, "%d\n", result);
        fclose(file_out);
    }

    return 0;

but it only writes the last number from the sequence. I'd be very grateful if someone could tell me what I am doing wrong. thanks maria

first try to open the file outside the while loop and run it again and close the files after the loop.

{
    FILE *file_in;
    File *file_out;
    file_in = fopen("roman.txt", "r");
    if (file_in == NULL) {
      printf("Error: unable to open "roman.txt.\n");
    exit(EXIT_FAILURE);
     }

    file_out = fopen("arabic.txt", "a");
     if (file_out == NULL) {
       printf("Error: unable to open ‘arabic.txt’\n");
    exit(EXIT_FAILURE);
     }   

    while (!feof(file_in))
    {
        fscanf(file_in, "%s", number);
        result = RomantoArabic(number, value);
        fprintf(file_out, "%d\n", result);
    }
      fclose(file_in);
      fclose(file_out);

    return 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM