[英]Reading from file, but I'm not able to print the last line?
我正在尝试使用fscanf从文件中读取(老师非常需要这样做,我个人会使用getline或其他方式),并且试图读取直到文件末尾-我的代码似乎可以正常工作,除了返回外循环时似乎并没有打印出我正在读取的文件的最后一行,而且我不确定为什么(当我调用readLine函数并打印出我进入那个函数里面)
如果有人可以查看我的代码并让我知道我要去哪里,我将非常感激。 (请忽略main中看起来很奇怪的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
最后一行被读取后,该文件是在年底。 您的函数仍然返回EXIT_SUCCESS(和最后一行),但是您还要检查EOF: ... && !feof(infile)
,因此处理在最后一行打印之前结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.