[英]Segmentation Fault(core dumped)
大家好,我得到了以下代碼:(我試圖讀取一個字符串並將其放在輸出文件中)
#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)
我不知道為什么:(請幫助
您需要檢查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
導致分段錯誤。
#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會觸發分段錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.