2016-09-10 8 views
0

fscanfを使ってファイルから読み込もうとしています(教師がかなり必要です、私は個人的にgetlineなどを使用します)、ファイルの最後まで読み込もうとしています。私が外側のループに戻るときに私が読んでいるファイルの最後の行を印刷していないように見えることを除いて、なぜ私はreadLine関数を呼び出すと印刷しますか?私がコードを見渡し、私が間違っている場所を教えてもらえれば、本当に感謝しています。ファイルから読み取っていますが、最後の行を印刷できません。

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

(if文の主、それは私はまだもらっていない将来のコードのためだ。で見て、むしろ奇妙なを無視してください)
#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 

答えて

0

最後の行が読み取られた後、ファイルは最後にです。あなたの関数はまだEXIT_SUCCESS(と最後の行)を返しますが、さらにEOF:... && !feof(infile)をチェックするので、最後の行が印刷される前に処理が終了します。

+0

それは意味があります、私は2つの条件を交換し、それは今完璧に動作します!ありがとう! –

関連する問題