CIODemo.c
#include <stdio.h> #include <time.h> #define INPUT_BUFFER_SIZE 100 * 1024 int main() { printf("Enter an input file name: "); char filename[1000]; gets(filename); FILE *inputFile = fopen(filename, "rb"); if (inputFile) { printf("Enter an output file name: "); gets(filename); FILE *outputFile = fopen(filename, "wb"); if (outputFile) { printf("Copying file... "); time_t startTime = time(NULL); char buffer[INPUT_BUFFER_SIZE]; while (!feof(inputFile)) { size_t numberOfObjects = fread(buffer, sizeof(char), INPUT_BUFFER_SIZE, inputFile); fwrite(buffer, sizeof(char), numberOfObjects, outputFile); } time_t endTime = time(NULL); printf("File copied, elapsed time: %u seconds ", endTime - startTime); fclose(inputFile); fclose(outputFile); } else printf("Cannot open file: %s", filename); } else printf("Cannot open file: %s", filename); return 0; }
以上为读写二进制文件的示例,若要读写文本文件,只需将文件访问模式更改为r(读)和w(写)即可