C 文本反转总是在最后打印不需要的 '%'
C text inverting always prints unwanted '%' in the end
我有这个小代码,它只能逐个字符地反转文件中的文本,而且它工作得很好,问题是它总是在末尾添加一个“%”。
FILE *fd;
int main (int argc, char *argv[]) {
if ((fd = fopen(argv[1], "r")) != NULL){
int ft = 0;
int i = 0;
fseek(fd, 0, SEEK_END);
ft = ftell(fd);
while(i < ft)
{
i++;
fseek(fd, -i, SEEK_END);
printf("%c", fgetc(fd));
}
printf(" ");
fseek(fd, 0, SEEK_END);
fclose(fd);
}
else {
perror ("File does not exist !!!\n\a");
}
return 0;
}
输入的文字是:Taco cat
输出为:tac ocaT %
所以我找不到摆脱这个讨厌的 % 符号的方法。
我在 linuxmint。
%
是您的 shell 提示符。它不是来自程序。它看起来很奇怪的原因是您忘记在字符串末尾打印 \n
。
使用 FILE
包括 <stdio.h>
header。
检查文件打开可以在 if 语句之外进行,这样可以提高可读性。
完成后添加一个\n
输出。
到目前为止的代码
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *fd = fopen(argv[1], "r");
if (fd == NULL) {
perror("File does not exist !!!\n\a");
}
int ft = 0;
int i = 0;
fseek(fd, 0, SEEK_END);
ft = ftell(fd);
while (i < ft) {
i++;
fseek(fd, -i, SEEK_END);
printf("%c", fgetc(fd));
}
printf(" ");
fseek(fd, 0, SEEK_END);
fclose(fd);
printf("\n");
return 0;
}
有关 fseek()
的更多准确性检查结果,成功时 return 为零。
这里从联机帮助页中获取,man fseek
。
RETURN VALUE
The rewind() function returns no value. Upon successful completion, fgetpos(), fseek(), fsetpos() re‐
turn 0, and ftell() returns the current offset. Otherwise, -1 is returned and errno is set to indi‐
cate the error.
我有这个小代码,它只能逐个字符地反转文件中的文本,而且它工作得很好,问题是它总是在末尾添加一个“%”。
FILE *fd;
int main (int argc, char *argv[]) {
if ((fd = fopen(argv[1], "r")) != NULL){
int ft = 0;
int i = 0;
fseek(fd, 0, SEEK_END);
ft = ftell(fd);
while(i < ft)
{
i++;
fseek(fd, -i, SEEK_END);
printf("%c", fgetc(fd));
}
printf(" ");
fseek(fd, 0, SEEK_END);
fclose(fd);
}
else {
perror ("File does not exist !!!\n\a");
}
return 0;
}
输入的文字是:Taco cat
输出为:tac ocaT %
所以我找不到摆脱这个讨厌的 % 符号的方法。 我在 linuxmint。
%
是您的 shell 提示符。它不是来自程序。它看起来很奇怪的原因是您忘记在字符串末尾打印 \n
。
使用 FILE
包括 <stdio.h>
header。
检查文件打开可以在 if 语句之外进行,这样可以提高可读性。
完成后添加一个\n
输出。
到目前为止的代码
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *fd = fopen(argv[1], "r");
if (fd == NULL) {
perror("File does not exist !!!\n\a");
}
int ft = 0;
int i = 0;
fseek(fd, 0, SEEK_END);
ft = ftell(fd);
while (i < ft) {
i++;
fseek(fd, -i, SEEK_END);
printf("%c", fgetc(fd));
}
printf(" ");
fseek(fd, 0, SEEK_END);
fclose(fd);
printf("\n");
return 0;
}
有关 fseek()
的更多准确性检查结果,成功时 return 为零。
这里从联机帮助页中获取,man fseek
。
RETURN VALUE
The rewind() function returns no value. Upon successful completion, fgetpos(), fseek(), fsetpos() re‐ turn 0, and ftell() returns the current offset. Otherwise, -1 is returned and errno is set to indi‐ cate the error.