linux fopen 段错误,段错误而使用的fopen

本文探讨了一段C语言代码中出现的段错误问题,问题出现在使用`fprintf`函数尝试写入文件时。错误在于使用了错误的格式说明符,将`char`值传递给了期望`char*`的`%s`格式。修复这个问题需要确保正确地传递字符串指针。同时,代码在`fopen`成功后进行了测试打印,确认了文件打开操作并未导致错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我从下面的代码的第二行接收段错误:段错误而使用的fopen

FILE *output = NULL;

output = fopen("./output2.txt", "w+");

我不认为这是某种形式的破坏内存错误的,因为当我改变w +来河它运行时没有段错误。此外,它似乎创建该文件之前它segfaults。

编辑:原来mrbatch是正确

我所有的代码以供参考:

void writeFile(const char *header, int numRows, int numCols, int **grades, const char *outFile)

{

printf("writefile success\n");

int i, j;

FILE *output = NULL;

output = fopen("./output2.txt", "w+"); // ERROR HERE (I was wrong, keep reading)

printf("testestestsetsete\n\n\n"); //based off the commenters, this code

//IS reached but is never printed

fprintf(output, "%s", *header); //commenters stated error is here

//*header should be header

fprintf(output, "%d %d\n", numRows, numCols); //output the number or rows and columns at the second line

//output each grades(scores) in the processed 2D array grades

for(i = 0; i < numRows; i ++) { //loop through all rows

for(j = 0; j < numCols; j ++) //loop through all columns in the i row

{

if(j < numCols - 1)

fprintf(output, "%d ", grades[i][j]);

else

fprintf(output, "%d\n", grades[i][j]);

//printf("\"%d\" ", score);

}

//printf("\n");

}

fclose(output);

}

+0

错误实际上是您的'fopen'之后的第一个'fprintf'。 '%s'格式说明符需要一个'char *',并且你传递了一个'char'值('* header'),它试图将其解释为一个地址并导致段错误。 –

+0

我知道这不是因为我在代码中有一个测试printf(我在发布之前删除了它),这是在fopen之后和fprintf之前的。 –

+1

请用'printf'显示测试代码并重新运行测试。 'fopen'很好,但是'fprintf'最明显的不是。或者更好的是,注释掉'fopen'后面的'fprintf',看看会发生什么。 –

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值