あなたのファイルに似た小さな c ファイルを作成しました。C の i/o をよりよく理解するのに役立つことを願っています。
コード:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char fileNameOne[] = "test.txt";
char fileNameTwo[] = "new.txt";
FILE* oldFile;
FILE* newFile;
printf("The file being read from is: %s\n", fileNameOne);
//get a File pointer to the old file(file descriptor)
oldFile = fopen(fileNameOne, "r");
//get a File pointer to the new file(file descriptor)
//a+ is to open for read and writing and create if it doesnt exist
//if we did not specify a+, but w+ for writing, we would get an invalid file descriptor because the file does not exist
newFile = fopen(fileNameTwo, "a+");
if (newFile == 0) {
printf("error opening file\n");
exit(1);
}
//read everything from the old file into a buffer
char buffer[1024];
printf("Contents of old file:\n");
while (fread(buffer, 1, 1024, oldFile) != 0) {
//if fread returns zero, and end of file has occured
printf("%s", buffer);
//directly write the contents of fileone to filetwo
fwrite(buffer, 1, 1024, newFile);
}
printf("The file %s has been read and written to %s\n", fileNameOne, fileNameTwo);
printf("Verification: Contents of file two:\n");
//move the offset back to the beginning of the file
rewind(newFile);
while (fread(buffer, 1, 1024, newFile)!= 0) {
printf("%s", buffer);
}
printf("\nEnd of file 2\n");
}
同じディレクトリに test というテキスト ファイルを作成し、そこにゴミを書き込んだだけです。これが出力です。
出力:
The file being read from is: test.txt
Contents of old file:
Hi, my name is Jack!
HAHAHAH
YOU DON"T even know!
The file test.txt has been read and written to new.txt
Verification: Contents of file two:
Hi, my name is Jack!
HAHAHAH
YOU DON"T even know!
End of file 2