上一篇文章中介绍了fgets函数,可以一次获取一行数据到一个buffer中。对应也有一个函数是fputs,可以一次将一行数据写入到一个文件中,同样,在写入之前要以w方式打开被写入的文件,具体代码如下:
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> int readFile(char* pfile, char* pwritefile) { FILE* pFile = fopen(pfile, "r"); // 如果要写文件,需要以w方式打开 FILE* pWriteFile = fopen(pwritefile, "w"); if (NULL == pFile) return -1; if (NULL == pWriteFile) { // 打开要写的文件失败 fclose(pFile); return -2; } char buf[1024]; while (fgets(buf, 1024, pFile)) { // 将读取的buf使用fputs函数写入到pWriteFile关联的文件中 fputs(buf, pWriteFile); } fclose(pFile); fclose(pWriteFile); return 0; } int main(int argc, char* argv[]) { readFile("File.txt", "FileNew.txt"); system("pause"); return 0; }