我试着把我的文本读到前面,然后按相反的顺序打印到那个文件中,但是我的for循环似乎不起作用。另外,我的while循环正在计算999个字符,尽管它应该是800个或更多(记不清楚),我想可能是因为这两段之间有一个空行,但还是没有字符。
这是我的两个循环的代码-:
/*Reversing the file*/
char please;
char work[800];
int r, count, characters3;
characters3 = 0;
count = 0;
r = 0;
fgets(work, 800, outputfile);
while (work[count] != NULL)
{
characters3++;
count++;
}
printf("The number of characters to be copied is-: %d", characters3);
for (characters3; characters3 >= 0; characters3--)
{
please = work[characters3];
work[r] = please;
r++;
}
fprintf(outputfile, "%s", work);
/*Closing all the file streams*/
fclose(firstfile);
fclose(secondfile);
fclose(outputfile);
/*Message to direct the user to where the files are*/
printf("\n Merged the first and second files into the output file
and reversed it! \n Check the outputfile text inside the Debug folder!");
最佳答案
在你的代码中有几个巨大的概念缺陷。
第一个是你说它“似乎不起作用”,而没有说明你为什么这么想。仅仅运行代码就揭示了问题所在:根本没有任何输出。
这就是原因。您可以反转字符串,因此终止的零出现在新字符串的开头。然后打印该字符串–它立即在第一个字符处结束。
通过减少characters3
中循环的开始来解决这个问题。
接下来,为什么不打印一些中间结果呢?这样你就能看到发生了什么。
string: [This is a test.
]
The number of characters to be copied is-: 15
result: [
.tset aa test.
]
嘿,看,回车似乎有问题(它最终出现在行首),这正是应该发生的事情——毕竟,它是字符串的一部分——但更有可能不是你打算做的。
除此之外,你可以清楚地看到,倒车本身是不正确的!
现在的问题是,您正在从同一字符串读写:
please = work[characters3];
work[r] = please;
将结尾处的字符写入位置#0,减小结尾并增大开头,然后重复直到完成。所以,读/写的后半部分又开始把结尾字符从开头复制到结尾!
两种可能的解决方法:1。从一个字符串读取并写入一个新字符串或2。调整循环,使其在完成“一半”后停止复制(因为每次迭代要进行两次交换,所以只需要循环一半字符数)。
你还需要多想想交换意味着什么。实际上,您的代码覆盖了字符串中的一个字符。要正确交换两个字符,需要先在临时变量中保存一个字符。
void reverse (FILE *f)
{
char please, why;
char work[800];
int r, count, characters3;
characters3 = 0;
count = 0;
r = 0;
fgets(work, 800, f);
printf ("string: [%s]\n", work);
while (work[count] != 0)
{
characters3++;
count++;
}
characters3--; /* do not count last zero */
characters3--; /* do not count the return */
printf("The number of characters to be copied is-: %d\n", characters3);
for (characters3; characters3 >= (count>>1); characters3--)
{
please = work[characters3];
why = work[r];
work[r] = please;
work[characters3] = why;
r++;
}
printf ("result: [%s]\n", work);
}
最后一点:您不需要“手动”计算字符数,这是一个函数。只需要这个而不是
count
循环;characters3 = strlen(work);
关于c - 如何在C中的文件中反转文本?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41070585/