我收到以下 C++ 代码的“分段错误”:
#include <cstdio>
int main(int, char**) {
FILE *fp;
fp = fopen("~/work/dog.txt", "w");
fprintf(fp, "timer, timer3, timer5, timer6, timer7");
fclose(fp);
}
您的路径无效并且永远不会起作用,因此fopen
设置fp
为NULL
并且您会遇到段错误。提示:~
字符由 shell 扩展,你不能在fopen
.
您尝试做的正确、安全的实现可能如下所示。这是经过测试的。这也是理智的人不使用 C 编写的原因,除非他们没有其他方法:)
// main.cpp
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
int main(int, char**)
{
const char * home = getenv("HOME");
if (home == NULL || strlen(home) == 0 || access(home, F_OK) == -1) abort();
const char * subPath = "/work/dog.txt";
char * path = (char*)malloc(strlen(home) + strlen(subPath) + 1);
if (path == NULL) abort();
strcpy(path, home);
strcat(path, subPath);
FILE *fp = fopen(path, "w");
if (fp != NULL) {
fprintf(fp, "timer, timer3, timer5, timer6, timer7");
fclose(fp);
}
free(path);
}
一些东西:
您需要在使用 fp 之前检查它是否为 NULL,否则只要找不到文件,就会出现段错误。
您需要在将完整路径传递给 fopen 之前解析完整路径(fopen 不知道如何处理“~”)
例子:
FILE *fp = NULL;
char path[MAX];
char *home = getenv ("HOME");
if ( home )
{
snprintf(path, sizeof(path), "%s/work/dog.txt", home);
// now use path in fopen
fp = fopen(path, "w");
if ( fp )
{
fprintf(fp, "timer, timer3, timer5, timer6, timer7");
fclose(fp);
}
else
{
std::cout << "your dog is missing" << std::endl;
}
else
{
std::cout << "You are homeless" << std::endl;
}
发生段错误是您尝试打开的文件不存在。这与Qt无关。
测试 'fp' 的无效性并正确处理错误。就像是
FILE *fp = fopen("/path/to/work/dog.txt", "w");
if (fp == NULL)
{
printf("File does not exist.\n");
// throw exception or whatever.
}