2013-06-12 34 views
4

執行文件寫入分割的錯,我得到了下面的C++代碼中「segmentation fault」:使用文件指針

#include <cstdio> 

int main(int, char**) { 
    FILE *fp; 
    fp = fopen("~/work/dog.txt", "w"); 
    fprintf(fp, "timer, timer3, timer5, timer6, timer7"); 
    fclose(fp); 
} 
+0

順便說一句,這是使用C++編譯器編譯的C代碼,因爲沒有人在使用C++應該使用這些C API。他們很討厭。 –

+0

@Kuba Ober:有沒有辦法保留這些功能?我不能讓新的工作。 – user7185318

+0

你可以繼續使用它們,但是在C++代碼中它相當尷尬。 –

回答

9

你的路東西是無效的,不會有任何效果,從而fopenfpNULL,你會得到一個segfault。提示:~字符由shell擴展,您不能在fopen的參數中使用它。

您正在嘗試執行的操作的正確安全實現可能如下所示。這已經過測試。這也是爲什麼,除非他們有這樣做的沒有其他辦法吧:)

// 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); 
} 
0

段錯誤發生的情況是你試圖打開不存在的文件。這與Qt無關。

測試'fp'的無效性並正確處理錯誤。像

FILE *fp = fopen("/path/to/work/dog.txt", "w"); 
if (fp == NULL) 
{ 
    printf("File does not exist.\n"); 
    // throw exception or whatever. 
} 
+0

另請參閱Kube Ober的回答。 – Mankalas

1

有幾件事情理智的人不會用C寫的原因:

  • 你需要前檢查NULL FP使用它,否則無論何時找不到文件,您都會遇到段錯誤。

  • 你需要傳遞給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; 
}