简体   繁体   English

fprintf() 不在文件中打印

[英]The fprintf() doesn't print in a file

I'm trying to print a string inside a file but in reverse.我正在尝试在文件中打印一个字符串,但反过来。 But the fprintf doesn't print it into the file.但是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;
    
}

Can you help me?你能帮助我吗?

  • str[i] is char , so passing that to %s invokes undefined behavior and typically leads to Segmentation Fault because a typical valid address will take more than 1 byte. str[i]char ,因此将其传递给%s会调用未定义的行为,并且通常会导致分段错误,因为典型的有效地址将占用超过 1 个字节。
  • You should calculate the length of the string read and use that instead of fixed start point 49.您应该计算读取的字符串的长度并使用它而不是固定起点 49。
  • You forgot to print str[0] .你忘了打印str[0] Also you may not want the newline character to be reversed (brought to top).此外,您可能不希望换行符被反转(带到顶部)。

Instead of the for (i = 49; i > 0; i--) loop, try this:而不是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> should be added to use strlen() . #include <string.h>应添加以使用strlen()

Assuming you simply want to reverse the string and then print it to wherever, that can be easily done with the following code, assuming you know the string's length:假设您只是想反转字符串,然后将其打印到任何地方,可以使用以下代码轻松完成,假设您知道字符串的长度:

for(int i=0, k=len-1; i<(len/2); i++, k--)
{
    temp = str[k];
    str[k] = str[i];
    str[i] = temp;
}

You can then just fprintf the string in the usual way.然后,您可以以通常的方式fprintf字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM