2016-09-10 3 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을

#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

... 말이 맞습니다. 두 조건을 바꿨고 지금은 완벽하게 작동합니다! 감사! –