我正在尝试打开一个文件,看看文件中有多少行,单词,字符和句子。一切都编译得很好,但是当程序运行时,它打印指令然后出现“分段错误(核心转储)”错误。我知道文件打开正常,所以我猜我在processFile中做错了什么。帮助会很棒!
P.S。 #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;
}
答案 0 :(得分:0)
*行,*字等都是从未初始化为正确内存地址的指针。
如果你在main之外创建它们作为整数并删除所有*前缀它应该有用。
答案 1 :(得分:0)
使这些int不是指向int
的指针 *lines = 0,
*sentences = 0,
*characters = 0,
*words = 0;
删除每个中的*以及递增它们时
答案 2 :(得分:0)
at main:
int lines = 0,
words = 0,
sentences = 0,
characters = 0;
...
processFile(fileIn, &lines, &word,&sentences, &characters);
at processFile
processFile(FILE* fileIn, int* lines, int* word, int* sentences, int* characters){
...
}
请注意:
fscanf(fileIn, "%d", &ch)
&lt; - 错误
return *lines++;
&lt; - 不要返回