2015-05-29 70 views
1

我现在很困惑。我想创建一个文件并写入一个之前创建的字符串。但是当下面的代码被执行时,会发生分段错误并且程序终止。c - 打开文件时出现分段错误

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

该行声明如下。

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

首先,我认为会出现,因为的malloc的错误,但是这个代码不工作之一:

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

我在做什么错?在该行之前运行的代码中,我也使用了文件指针,但文件已关闭。

+4

那么,首先你不检查fopen的结果。 – OldProgrammer

+0

除了分配内容之外,你还会做任何事吗? –

+3

'fprintf(file,line)'的用法也很危险,因为变量'line'可能包含fomat说明符。考虑使用'fprintf(文件,“%s”,行)'。 –

回答

1

你的代码不好,因为你不检查错误。 output可能是一个空指针(而很可能是一个):

#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); 

你确定你有权限创建的CWD文件?

fopen()errno设置为发生故障时的错误代码。像往常一样strerror(errno)会给你这个错误代码的描述。

0

看看你有没有正确的文件名,并确保它在同一目录中,否则提供文件的完整路径。如果它错了,那么它将不会打开并确保文件权限。

#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; 
}