1

I was trying to create a program which exchange the data in file A and file B (so in the end file A will be rewritten with file B data and vice versa) and I was stuck in a infinite loop. I think the problem is with my fseek function. I know I can create a temporary file but I am trying to use fseek... for fun (no I just want to learn the correct way of using fseek).

Here are the code.

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
    char filename1[62];
    char filename2[62];
    int c1, c2;
    bool end1, end2;
    FILE *fp1;
    FILE *fp2;

    printf("ファイル1=");
    scanf("%s", filename1);

    printf("ファイル2=");
    scanf("%s", filename2);

    fp1 = fopen(filename1, "r+");
    fp2 = fopen(filename2, "r+");


    if (!fp1 || !fp2) printf("ファイルをオープンできません");
    else {
         end1 = false;
         end2 = false;

         while(end1 == false || end2 == false){
             if (end1 == false) c1 = fgetc(fp1);
             if (end2 == false) c2 = fgetc(fp2);

             if (c1 == EOF) end1 = true;
             if (c2 == EOF) end2 = true;

             if (end1 == false){
                 if (fseek(fp2, -1, SEEK_CUR) == 0){
                     fputc(c1, fp2);
                 }
             } else {
                 //fputc(" ", fp2);
             }

             if (end2 == false){
                 if (fseek(fp1, -1, SEEK_CUR) == 0){
                     fputc(c2, fp1);
                 }
             } else{
                 //fputc(" ", fp1);
             }

         }

         fclose(fp1);
         fclose(fp2);
     }

     return (0);
 }

This program was ran on Windows 10, using mingw compiler. The file in question was saved in shiftjis encoding.

Afiq
  • 23
  • 4
  • @dxiv I edited the code. Sorry for taking your time. – Afiq May 28 '20 at 02:29
  • 1
    See [Why is fseek or fflush always required between reading and writing in the update modes?](https://stackoverflow.com/questions/1713819/why-is-fseek-or-fflush-always-required-between-reading-and-writing-in-the-update). Easiest change would be to add an `fflush` after each `fputc`. – dxiv May 28 '20 at 02:47
  • @dxiv It worked now but the file end data is in a weird way. But I think that's because the file length is not the same. Now I can start editing the commented code. Thank you! Guess I need to reread fflush manual. – Afiq May 28 '20 at 02:53

0 Answers0