简体   繁体   English

c-打开文件时出现分段错误

[英]c - Segmentation faults while opening file

I'm getting really confused right now. 我现在真的很困惑。 I want to create a file and write to it a string which was created before. 我想创建一个文件并将其写入之前创建的字符串。 But when the following code gets executed there happens the segmentation fault error and the program terminates. 但是,当执行以下代码时,将发生分段错误错误,程序将终止。

FILE* output;
output = fopen("test.txt", "w");
fprintf(output, line);
fclose(output);

The line is declared as the following. 该行声明如下。

char* line = NULL;
line = malloc(1048576 + 1);

First I've considered that the error appears because of the malloc, but this code isn't working either: 首先,我认为该错误是由于malloc出现的,但是此代码也不起作用:

FILE* output;
output = fopen("test.txt", "w");
fprintf(output, "LBASDHASD");
fclose(output);

What am I doing wrong? 我究竟做错了什么? In the code which runs before that lines I've used a file pointer too but the file is already closed. 在那行之前运行的代码中,我也使用了文件指针,但是文件已经关闭。

Your code is bad as you do not check for errors. 您的代码不正确,因为您不检查错误。 output could be a NULL pointer (and is likely to be one): output可能是NULL指针(很可能是一个):

#include <errno.h>
#include <string.h>

FILE* output;
output = fopen("test.txt", "w");
if(!output){
   //handle the error
   printf("something went wrong: %s", strerror(errno));
   exit(1);
}
fprintf(output, "LBASDHASD");
fclose(output);

Are you sure you have permission to create the file in the CWD? 您确定您具有在CWD中创建文件的权限吗?

fopen() sets errno to an error code in case of a failure. 如果失败, fopen() errno为错误代码。 As usual strerror(errno) will give you a description of this error code. 像往常一样, strerror(errno)将为您提供此错误代码的描述。

See if you have the filename correctly or not and make sure it is in the same directory, otherwise provide the full path of the file. 查看文件名是否正确,并确保文件名位于同一目录中,否则请提供文件的完整路径。 If it is mistaken then it will not open and make sure of the file permission. 如果输入错误,它将无法打开并确保文件权限。

#include <stdio.h>

int main()
{
    FILE *output;
    output = fopen("test.txt","w");
    if(output==NULL)
    {
        printf("Error in opening the file");
        return 0;
    }
    fprintf(output, "%s", "LBASDHASD");
    fclose(output);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM