使用FILE指针执行文件写入的分段错误

时间:2013-06-12 16:29:34

标签: c++ c file-io

我得到以下C ++代码的“分段错误”:

#include <cstdio>

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

3 个答案:

答案 0 :(得分:9)

您的路径无效且永远不会有效,因此fopenfp设置为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);
}

答案 1 :(得分:1)

一些事情:

  • 你需要在使用前检查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;
}

答案 2 :(得分:0)

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.
}
相关问题