我正在尝试打开一个文件并查看文件中有多少行、单词、字符和句子。一切编译正常,但是当程序运行时,它会打印指令,然后出现“分段错误(核心转储)”错误。我知道文件可以正常打开,所以我猜我在 processFile 中做错了什么。帮助会很棒!
PS #include "lib09.h" 是 main() 之后的三个函数
#include <stdio.h>
#include <stdlib.h>
#include "lib09.h"
int main(void)
{
FILE *fileIn;
int *lines = 0,
*words = 0,
*sentences = 0,
*characters = 0;
printInstructions();
fileIn = fopen("input09.txt", "r");
if (fileIn == NULL)
{
printf("\n\nERROR\n");
printf("FILE DOES NOT EXIST.\n");
printf("TRY AGAIN\n\n");
}
else
{
processFile(fileIn);
printReport(lines, words, characters, sentences);
}
return 0;
}
//
//Prints Instructions
//
void printInstructions()
{
printf("\n====================================================\n");
printf(" Program reads a file and returns the number of \n");
printf("lines, words, characters, and sentences in the file.\n");
printf("====================================================\n\n");
return;
}
//
//Processes File
//
int processFile(FILE *fileIn)
{
int ch,
*lines = 0,
*sentences = 0,
*characters = 0,
*words = 0;
while(fscanf(fileIn, "%d", &ch) != EOF)
{
ch = fgetc(fileIn);
if(ch == '\n' || ch == 60)
return *lines++;
if(ch == '.')
return *sentences++;
if(ch != ' ' || ch != '.' || ch != '\n')
return *characters++;
if(ch == ' ')
return *words++;
}
fclose(fileIn);
return 0;
}
//
//Prints Values from File
//
void printReport(int *words, int *lines, int *characters, int *sentences)
{
printf("This file contains %d lines.\n", *lines);
printf("This file contains %d words.\n", *words);
printf("This file contains %d characters.\n", *characters);
printf("This file contains %d sentences.\n\n", *sentences);
return;
}