[英]Segmentation fault executing file writing using FILE pointer
我得到以下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;
}
Segfault發生的是您嘗試打開的文件不存在。 這與Qt無關。
測試'fp'的無效並正確處理錯誤。 就像是
FILE *fp = fopen("/path/to/work/dog.txt", "w");
if (fp == NULL)
{
printf("File does not exist.\n");
// throw exception or whatever.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.