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.