我创建了一个类似于你的小 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