从文件中读取,但我无法打印最后一行?

时间:2016-09-10 23:44:18

标签: c file-handling

我试图使用fscanf读取文件(老师非常需要这个,我个人会使用getline或其他东西)并且我试图读取直到结束文件 - 我的代码似乎工作得很好,除了它似乎打印出文件的最后一行,当我返回到外循环时,我正在阅读,我不知道为什么(当我调用readLine函数并打印出 函数内部的行时,它会打印出来)

如果有人可以查看我的代码并让我知道我哪里出错了,我真的很感激。 (请忽略主要的相当奇怪的if语句,以及我尚未获得的未来代码。)

most_freq.h

#ifndef MOST_FREQ_H_
#define MOST_FREQ_H_

#include <stdio.h>

//used to hold each "word" in the list
typedef struct word_node
{
char *word;
unsigned int freq; //frequency of word 
struct word_node *next;
} word_node;

struct node *readStringList(FILE *infile);

int readLine(FILE *infile, char * line_buffer);

struct node *getMostFrequent(struct word_node *head, unsigned int num_to_select);

void printStringList(struct word_node *head);

void freeStringList(struct word_node *head);

int InsertAtEnd(char * word, word_node *head);

char *strip_copy(const char *s); //removes any new line characters from strings

#endif

most_freq.c

#include "most_freq.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct word_node *head = NULL; //unchanging head node
char* str_buffer = NULL;

struct node *readStringList(FILE *infile) {
    char* temp_buffer = malloc (sizeof(char) * 255); //buffer for 255 chars
    while(readLine(infile, temp_buffer) == EXIT_SUCCESS && !feof(infile)) { //while there is still something to be read from the file
        printf("Retrieved Line: %s\n", str_buffer);
    }
}
int readLine(FILE *infile, char * line_buffer) {
   fscanf(infile, "%s", line_buffer);
   str_buffer = strdup(line_buffer);
   if(str_buffer[0] != '\0' || strcmp(str_buffer, "") != 0) {
    return EXIT_SUCCESS; //return success code
   }
   else {
    return EXIT_FAILURE; //return failure code
   }
}

int InsertAtEnd(char * word, word_node *head){
}

void printStringList(struct word_node *top) {
}

char *strip_copy(const char *s) {
}

int main(int argc, char *argv[])
{
    if (argc == 2) // no arguments were passed
    {
        FILE *file = fopen(argv[1], "r"); /* "r" = open for reading, the first command is stored in argv[1] */
        if ( file == 0 )
        {
            printf( "Could not open file.\n" );
        }
        else
        {
            readStringList(file);
        }
    }
    else if (argc < 3) {
        printf("You didn't pass the proper arguments! The necessary arguments are: <number of most frequent words to print> <file to read>\n");
    }
}

文本文件

foofoo
dog
cat
dog
moom
csci401isfun
moon$
foofoo
moom.
dog
moom
doggod
dog3
f34rm3
foofoo
cat

1 个答案:

答案 0 :(得分:0)

读完最后一行后,文件最后是。您的函数仍然返回EXIT_SUCCESS(和最后一行),但您还要检查EOF:... && !feof(infile),因此处理在最后一行打印之前结束。