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

jdl*_*jdl 4 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);
}
Run Code Online (Sandbox Code Playgroud)

Rei*_*ica 9

您的路径无效,永远不会工作,因此fopen设置fpNULL,您会得到一个段错误.提示:~字符由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);
}
Run Code Online (Sandbox Code Playgroud)