gpt4 book ai didi

C 编程 我试图从 2 个 txt 文件切换内容

转载 作者:行者123 更新时间:2023-11-30 14:48:15 24 4
gpt4 key购买 nike

我正在尝试切换 2 个 txt 文件的内容,它们只有带字符的行。

我尝试这样做,程序编译但不修改文本文件中的任何内容。还有其他方法可以做到这一点吗?

FILE *f, *p;
char linha[TAM], linha2[TAM];

f =fopen("texto.txt", "r");

if(f==NULL)
{
printf("Erro ao abrir ficheiro");
fclose(f);
return;
}

p =fopen("texto2.txt", "r");

if(p==NULL)
{
printf("Erro ao abrir ficheiro");
fclose(p);
return;
}


while( fgets(linha,TAM,f) != NULL || fgets(linha2,TAM,p) != NULL )
{
if(strcmp(linha, "") != 0)
{
fprintf(p, "%s", linha);
}

if(strcmp(linha2, "") != 0)
{
fprintf(f, "%s", linha2);
}
}

fclose(f);
fclose(p);


return 0;

}

最佳答案

正如 @PaulStelian 所暗示的那样,直接交换是有问题的。以交换两个变量为例:要使其起作用,必须将一个变量的数据临时存储在某处。 (或者使用 XOR 交换,这很不错,但是很老套,并且适用于二进制数据。)

你最好的选择可能是复制一个文件,然后像这样进行交换

duplicateFile = copy(file1);
file1 = file2;
file2 = duplicateFile;
<小时/>

对于fopen,使用r+选项打开文件以进行读取和写入。 r 只是打开它进行阅读。

来自man fopen:

r Open text file for reading. The stream is positioned at the beginning of the file.

r+ Open for reading and writing. The stream is positioned at the beginning of the file.

关于C 编程 我试图从 2 个 txt 文件切换内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50543638/

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