【发布时间】:2020-10-22 11:43:41
【问题描述】:
我想使用 c FILE 进行复制/粘贴,但我也需要添加读/写缓冲区,但我不知道如何添加它。有没有类似普通读/写的功能。代码如下。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[]) {
FILE* fsource, * fdestination;
printf("enter the name of source file:\n");
char sourceName[20], destinationName[20];
strcpy(sourceName, argv[1]);
strcpy(destinationName, argv[2]);
fsource = fopen(sourceName, "r");
if (fsource == NULL)
printf("read file did not open\n");
else
printf("read file opened sucessfully!\n");
fdestination = fopen(destinationName, "w");
if (fdestination == NULL)
printf("write file did not open\n");
else
printf("write file opened sucessfully!\n");
char pen = fgets(fsource);
while (pen != EOF)
{
fputc(pen, fdestination);
pen = fgets(fsource);
}
fclose(fsource);
fclose(fdestination);
return 0;
}
【问题讨论】:
-
您可能正在寻找
fread和fwrite。 -
我把 fgets 改成了 fgetc j
-
正确的错误消息被写入标准错误并包含失败的原因:
if( fsource == NULL ) { perror(sourceName); exit(EXIT_FAILURE; } -
你的问题对我来说毫无意义。
fgets和fgetc是缓冲读取。你想做什么? -
不要复制 argv。如果您想要一个比
argv[1]更具可读性的名称(这是一件非常合理的事情),则无需复制数据。相反,只需执行const char *sourceName = argv[1];通过将 sourceName 设置为大小为 20 的数组,然后使用未经检查的strcpy,您会暴露一个简单的缓冲区溢出。