我正试图在文件中打印一个字符串,但相反。但是fprintf
不会将其打印到文件中。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <iso646.h>
#include <errno.h>
#include <stddef.h>
#define dim 50
int main(int argc, char const *argv[]) {
FILE *fin;
FILE *fout;
char str[dim];
char nomefilein[dim];
char nomefileout[dim];
int i;
printf("Inserisci il nome del file da leggere:n");
scanf("%s",nomefilein);
printf("Inserisci il nome del file da scrivere:n");
scanf("%s",nomefileout);
fin=fopen(nomefilein, "r");
fout=fopen(nomefileout, "w");
while (fgets(str, dim, fin)!=NULL) {
printf("%s",str);
for (i = 49; i > 0; i--) {
fprintf(fout, "%s", str[i]);
}
}
fclose(fin);
return 0;
}
你能帮我吗?
str[i]
是char
,因此将其传递给%s
会调用未定义的行为,通常会导致分段故障,因为典型的有效地址将占用超过1个字节- 您应该计算读取的字符串的长度,并使用它来代替固定的起点49
- 您忘记打印
str[0]
。此外,您可能不希望换行符反转(置于顶部(
不要使用for (i = 49; i > 0; i--)
循环,请尝试以下操作:
i = strlen(str); /* get the length of string */
if (i > 0) {
i--;
if (i > 0 && str[i] == 'n') i--; /* ignore the last newline character */
for (; i >= 0; i--) { /* use >=, not > */
fputc(str[i], fout); /* you won't need fprintf() to print single character */
}
fputc('n', fout); /* print newline character at end of line */
}
应添加#include <string.h>
以使用strlen()
。
假设您只想反转字符串,然后将其打印到任何位置,那么使用以下代码可以很容易地完成,假设您知道字符串的长度:
for(int i=0, k=len-1; i<(len/2); i++, k--)
{
temp = str[k];
str[k] = str[i];
str[i] = temp;
}
然后,您可以用通常的方式只fprintf
字符串。