c语言 - fprintf 像我 5 岁一样解释



我正在尝试将一些字符串写入文件中。这是没有警告的情况,但是当我运行A.Out时,它可以进行。但是,它确实创建了目标文件。我是C的新手,所以我为自己的格式和其他缺点表示歉意。这是我的代码:

#include<stdio.h>
int main (void)
{
    FILE *fp_out;
    char str1[]="four score and seven years ago our";
    char str2[]="fathers broughy forth on this continent,";
    char str3[]="a new nation, concieved in Liberty and dedicated";
    char str4[]="to the proposition that all men are created equal.";
    fp_out=fopen("my_file", "w");
    if(fp_out!=NULL)
    {
        fprintf(fp_out,"%sn", str1[100]);
        fprintf(fp_out,"%sn", str2[100]);
        fprintf(fp_out,"%sn", str3[100]);
        fprintf(fp_out,"%sn", str4[100]);
        fclose(fp_out);
    }
    else
        printf("The file "my_file" couldn't be openedn");
    return 0;
}

您应该在fprintf()上阅读手册。

int fprintf(FILE *stream, const char *format, ...);

在您使用%s的格式字符串中,这意味着您将通过fprintf()字符串。

这是一串字符:

char str1[]="four score and seven years ago our";

这就是您打印字符串的方式:

fprintf(fp_out,"%sn", str1);

您想在这里做什么:

fprintf(fp_out,"%sn", str1[100]);

是打印101 st str1的字符,它的时间不长,因此您正在尝试访问内存方式,超出了您的数组的拥有...更不用说您正在通过格式字符串的字符字符串期望引起ub的字符串。

您只需将指针传递给数组

if(fp_out!=NULL)
{
    fprintf(fp_out,"%sn", str1);
    fprintf(fp_out,"%sn", str2);
    fprintf(fp_out,"%sn", str3);
    fprintf(fp_out,"%sn", str4);
    fclose(fp_out);
}

在您的代码中,'str1 [100]'表示从str1获取我的第100个字符。这将是范围0到255的单个字符。您的格式字符串为'%s',这意味着"我将向您传递一个指针到字符串"。您通过了一个字符(实际上只是一个数字),因此您有效地给了指针&lt; 255-这是一个非法地址,因此SEG错误。

在正确的代码中,'str1'是指向字符串的指针,因此有效。在您的示例中,str1没有接近100个字符,因此结果可能是任何字符(包括额外的seg故障)。

记住:c经常(尤其是printf)不在乎您的传递。如果您错了...麻烦。

哦...和...当我说100个时,它们是从0编号(实际上是101st)

当您尝试访问无权访问的内存时,分割故障是生成的错误。在您的代码中,您将str1 [100]传递给printf for a%s规格。%s规格期望char*(字符指针)。STR1 [100]本质上是垃圾,因为它在您声明的字符串之外。访问str1 [100]可能不会生成分段故障,尽管可能会根据最终指向的堆栈中的位置。但是,printf采用了您给它的垃圾,并试图将其作为角色指针将其解释,从而导致分割故障。校正的代码在下面。

#include<stdio.h>
int main (void)
{
    FILE *fp_out;
    char str1[]="four score and seven years ago our";
    char str2[]="fathers broughy forth on this continent,";
    char str3[]="a new nation, concieved in Liberty and dedicated";
    char str4[]="to the proposition that all men are created equal.";
    fp_out=fopen("my_file", "w");
    if(fp_out!=NULL)
    {
        fprintf(fp_out,"%sn", str1);
        fprintf(fp_out,"%sn", str2);
        fprintf(fp_out,"%sn", str3);
        fprintf(fp_out,"%sn", str4);
        fclose(fp_out);
    }
    else
        printf("The file "my_file" couldn't be openedn");
    return 0;
}

您在str1[100]上没有任何字符。使用指向null终止字符串的角色指针。

    char *str1 ="four score and seven years ago our";
    char *str2 ="fathers broughy forth on this continent,";
    char *str3 ="a new nation, concieved in Liberty and dedicated";
    char *str4 ="to the proposition that all men are created equal.";

    if(fp_out!=NULL)
    {
        fprintf(fp_out,"%sn", str1);
        fprintf(fp_out,"%sn", str2);
        fprintf(fp_out,"%sn", str3);
        fprintf(fp_out,"%sn", str4);
        fclose(fp_out);
    }

最新更新