2013-10-16 147 views
0

嘿家伙我有这样的代码:(IM试图读取一个字符串,并把它的输出文件中)分段错误(核心转储)

#include "structs.h" 
#include <stdio.h> 
#include <stdlib.h> 
int main() { 
    FILE* input = fopen("journal.txt", "r"); 
    FILE* output = fopen("output.txt", "w"); 
    char date[9]; 

    if(ferror(input) || ferror(output)) { 
    perror("Error opening input/output file\n"); 
    } 

    fscanf(input, "%s", date); 
    fgets(date, 9, input); 
    fputs(date, output); 
    fclose(input); 
    fclose(output); 
    return 0; 
} 

编译正确,但在运行时,它显示了错误

Segmentation fault (core dumped) 

我不知道为什么:(请帮助

+2

如果文件无法打开,'fopen'返回NULL。你不检查这个。 – Zeta

+3

如果你使用'* nix',你可以使用[* gdb *](http://www.unknownroad.com/rtfm/gdbtut/gdbsegfault.html) –

+2

为什么你首先'fscanf'ing,然后*也'* fgets'到'日期'? – Kninnug

回答

5

你需要检查是否fopen回报NULL

#include <stdio.h> 
#include <stdlib.h> 
int main() { 
    FILE * input; 
    FILE * output; 
    char date[9]; 

    input = fopen("journal.txt", "r"); 
    if(input == NULL){ 
    perror("Could not open input file"); 
    return -1; 
    } 

    output = fopen("output.txt", "w"); 
    if(output == NULL){ 
    perror("Could not open output file"); 
    fclose(input); 
    return -1; 
    } 
/* ... snip ... */ 

您的输入文件可能不存在。在NULL上调用ferror会导致分段错误。

0
#include <stdio.h> 
#include <stdlib.h> 

    int main() 
{ 
FILE* input = fopen("journal.txt", "r"); 
FILE* output = fopen("output.txt", "w"); 
char date[9]; 

if(input) 
{ 
    fscanf(input, "%s", date); 
    fgets(date, 9, input); 
} 
else 
{ 
    printf("error opening the file"); 
} 

if(output) 
{ 
    fputs(date, output); 
} 

else 
{ 
    printf("error opening the file"); 

} 

你正在接受分段错误,你是从一个不存在的文件“journal.txt”阅读并呼吁FERROR触发段错误。