gpt4 book ai didi

c - 当 fprintf 遇到 a 时,它会使我的程序崩溃\n

转载 作者:行者123 更新时间:2023-11-30 20:04:13 24 4
gpt4 key购买 nike

我试图在 .txt 文件中生成报告,但是当我的 fprintf 遇到 \n 时,它崩溃了。这是我关于打开文件和崩溃的代码:

FILE *f;
f = fopen("estructuras.txt", "w");
fprintf(f, "");
printf("3"); //This is the last thing I see.
fprintf(f, "TEXT TO INPUT\n")
fclose(f);

最佳答案

问题是你没有检查文件是否打开。如果失败,它将返回 NULL,这会对 fprintf 造成不好的影响。

你的第一个fprintf(f, "");是一个空操作。打印空字符串不会执行任何操作,因此“有效”(尽管我怀疑这是有保证的)。 printf("3"); 对 stdout 执行操作,并且不受失败的 fopen 影响。 fprintf(f, "TEXT TO INPUT\n") 最后尝试打印到 NULL 并呕吐。

必须检查所有系统调用。它们在出错时都有不同的返回值。 fopen 返回 NULL,错误位于 errno 中。有很多方法可以进行 fopen 错误处理,这是我喜欢的一种,它为用户提供了调试问题的信息。

#include <string.h>    // for strerror()
#include <errno.h> // for errno
#include <stdio.h>
#include <stdlib.h>

int main(){
// Put the filename in a variable so it can be used in the
// error message without needing to be copied.
char file[] = "estructuras.txt";

FILE *fp = fopen(file, "w");
if( fp == NULL ) {
// Display the filename, what you were doing with it, and why it wouldn't open.
fprintf(stderr, "Could not open '%s' for writing: %s\n", file, strerror(errno));
exit(-1);
}
}

strerror(errno) 将数字 errno 错误代码转换为人类可读的字符串。文件名周围有引号,以防出现额外的空格。

因此您会收到类似 Could not open 'estructuras.txt': No such file or directory 的错误。

关于c - 当 fprintf 遇到 a 时,它会使我的程序崩溃\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43021609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com