使用文件指针执行文件写入的分段错误 我为下面的C++代码得到了一个“分割错误”: #include <cstdio> int main(int, char**) { FILE *fp; fp = fopen("~/work/dog.txt", "w"); fprintf(fp, "timer, timer3, timer5, timer6, timer7"); fclose(fp); } #包括 int main(int,char**){ 文件*fp; fp=fopen(“~/work/dog.txt”,“w”); fprintf(fp,“定时器,定时器3,定时器5,定时器6,定时器7”); fclose(fp); }

使用文件指针执行文件写入的分段错误 我为下面的C++代码得到了一个“分割错误”: #include <cstdio> int main(int, char**) { FILE *fp; fp = fopen("~/work/dog.txt", "w"); fprintf(fp, "timer, timer3, timer5, timer6, timer7"); fclose(fp); } #包括 int main(int,char**){ 文件*fp; fp=fopen(“~/work/dog.txt”,“w”); fprintf(fp,“定时器,定时器3,定时器5,定时器6,定时器7”); fclose(fp); },c++,c,file-io,C++,C,File Io,如果您试图打开的文件不存在,则会发生错误。这与Qt无关 测试“fp”的空值并正确处理错误。差不多 FILE *fp = fopen("/path/to/work/dog.txt", "w"); if (fp == NULL) { printf("File does not exist.\n"); // throw exception or whatever. } 您的路径无效且永远不会工作,因此fopen将fp设置为NULL,您将得到一个segfault。提示:~字符由shel

如果您试图打开的文件不存在,则会发生错误。这与Qt无关

测试“fp”的空值并正确处理错误。差不多

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

您的路径无效且永远不会工作,因此
fopen
fp
设置为
NULL
,您将得到一个segfault。提示:
~
字符由shell展开,您不能在
fopen
的参数中使用它

正确、安全地实现您正在尝试执行的操作可能如下所示。这是经过测试的。这也是理智的人不使用C语言写作的原因,除非他们没有其他方法:)

//main.cpp
#包括
#包括
#包括
#包括
int main(int,char**)
{
const char*home=getenv(“home”);
如果(home==NULL | | strlen(home)==0 | |访问(home,F|u OK)==-1)中止();
const char*subPath=“/work/dog.txt”;
char*path=(char*)malloc(strlen(home)+strlen(subPath)+1);
如果(path==NULL)中止();
strcpy(路径,主页);
strcat(路径,子路径);
文件*fp=fopen(路径,“w”);
如果(fp!=NULL){
fprintf(fp,“定时器,定时器3,定时器5,定时器6,定时器7”);
fclose(fp);
}
自由(路径);
}
有几件事:

  • 在使用它之前,您需要检查fp是否为NULL,否则每当找不到该文件时,您将得到一个segfault

  • 在将其传递给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;
}
FILE*fp=NULL;
字符路径[MAX];
char*home=getenv(“home”);
如果(家)
{
snprintf(路径,sizeof(路径),“%s/work/dog.txt”,home);
//现在在fopen中使用path
fp=fopen(路径“w”);
if(fp)
{
fprintf(fp,“定时器,定时器3,定时器5,定时器6,定时器7”);
fclose(fp);
}
其他的
{

Kube Ober:你的答案也是。BTW,这是用C++编译器编译的C代码,因为没有人做C++应该使用那些C API。它们很讨厌。Kuba Ober:没有办法保存这些函数吗?我不能让新的函数工作。你可以继续使用它们,但是在C++代码中它相当笨拙。
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;
}