#include
#include "stdlib.h"
// 字符串读写函数: 将字符串追加到指定文件中,并显示出来
void testFgetsFputs(){
FILE *fp;
// 要写入的字符串
char str[100];
// 文件路径
char filePath[20];
// 从文件中读出的字符串存放到该数组中
char s[100];
printf("输入字符串:\n");
gets(str);
printf("输入文件路径:\n");
gets(filePath);
// 追加方式打开文件
if((fp = fopen(filePath, "a")) != NULL){
// 将字符串写入文件
fputs(str, fp);
fclose(fp);
}else{
printf("打开文件失败\n");
exit(0);
}
if((fp = fopen(filePath, "r")) != NULL){
printf("%s文件内容:\n", filePath);
while(fgets(s, sizeof(s), fp)){
// 将fp所指文件中的字符串读出到程序
printf("%s", s);
}
}
fclose(fp);
}
// 字符串读写函数:复制文件
void testCopyFile(){
FILE *in;
FILE *out;
char inFile[20], outputFile[20];
// 从源文件中读取的字符串
char s[100];
printf("请输入被复制文件名:\n");
gets(inFile);
printf("请输入新建文件名:\n");
gets(outputFile);
if((in = fopen(inFile, "r")) == NULL){
printf("打开文件 %s 失败\n", inFile);
exit(0);
}
if((out = fopen(outputFile, "w")) == NULL){
printf("不能建立 %s 文件\n", outputFile);
exit(0);
}
while(fgets(s, sizeof(s), in)){
// 将in指向的文件内容复制到out指向的文件中
fputs(s, out);
}
printf("复制完成\n");
fclose(in);
fclose(out);
}
int main() {
// 字符串读写函数: 将字符串追加到指定文件中,并显示出来
// testFgetsFputs();
// 字符串读写函数:复制文件
testCopyFile();
return 0;
}