gpt4 book ai didi

c - C中的文件操作

转载 作者:太空宇宙 更新时间:2023-11-04 07:07:24 25 4
gpt4 key购买 nike

最近,我开始研究 C 中的文件操作,并且成功地将一个文件的内容复制到另一个文件。

我先一步从文件的开头读取文件的内容,然后在同一个文件的末尾写入相同的内容。 (类似于追加)。但我无法这样做。

这是我编写的代码。任何人都可以建议,我在这里犯了什么错误吗?

#include <stdio.h>

int main(int argc, char **argv)
{
int size = 0, index = 0;

char byte = 0;

FILE *fp_read, *fp_write;

if ((fp_read = fopen(argv[1], "r+")) == NULL)
{
printf("Unable to Open File %s\n", argv[1]);
}

fp_write = fp_read;

fseek(fp_write, 0, SEEK_END);

size = ftell(fp_write);

printf("The Size of the file %s:\t%d\n", argv[1], size);

for (index = 0; index < size; index++)
{
if (fread(&byte, 1, 1, fp_read) != 1)
{
printf("Unable to Read from the file at Location:\t%d\n", index);
}

if (fwrite(&byte, 1, 1, fp_write) != 1)
{
printf("Unable to Write to the file at Location:\t%d\n", index);
}
}

if (fclose(fp_read))
{
printf("Unsuccessful in Closed the File\n");
}

return 0;
}

问候,

漩涡鸣人

最佳答案

你的错误是将 fp_readfp_write 当作它们没有指向同一个 FILE 对象。

关于c - C中的文件操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31437871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com