-2

我正在尝试打开一个文件并查看文件中有多少行、单词、字符和句子。一切编译正常,但是当程序运行时,它会打印指令,然后出现“分段错误(核心转储)”错误。我知道文件可以正常打开,所以我猜我在 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;
}
4

3 回答 3

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){
...
}

note:

fscanf(fileIn, "%d", &ch) <- wrong

return *lines++; <- do not return

于 2013-04-11T15:06:24.780 回答
0

使这些 int 不是指向 int 的指针

 *lines = 0,
 *sentences = 0,
 *characters = 0,
 *words = 0;

通过删除每个中的 * 以及当你增加它们时

于 2013-04-11T14:51:06.477 回答
0

*lines、*words 等都是从未初始化到正确内存地址的指针。

如果您在 main 之外将它们创建为整数并删除所有 *prefixes 它应该可以工作。

于 2013-04-11T14:49:56.433 回答