我正在尝试打开一个文件并查看文件中有多少行、单词、字符和句子。一切都编译得很好,但是当程序运行时,它会打印指令,然后出现“段错误(核心转储)”错误。我知道文件打开得很好,所以我猜我在 processFile 中做错了什么。帮助会很棒!
附注#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;
}
最佳答案
主要:
int lines = 0,
words = 0,
sentences = 0,
characters = 0;
...
processFile(fileIn, &lines, &word,&sentences, &characters);
在进程文件
processFile(FILE* fileIn, int* lines, int* word, int* sentences, int* characters){
...
}
注意:
fscanf(fileIn, "%d", &ch)
<- 错误
return *lines++;
<- 不返回
关于c - 我遇到了段错误 C 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15951817/