【问题标题】:Reading from file, but I'm not able to print the last line?从文件读取,但我无法打印最后一行?
【发布时间】:2016-09-10 23:44:17
【问题描述】:

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

如果有人可以查看我的代码并告诉我哪里出错了,我将不胜感激。 (请忽略 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

【问题讨论】:

    标签: c file-handling


    【解决方案1】:

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

    【讨论】:

    • 那...有道理,我交换了这两个条件,现在它可以正常工作了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    相关资源
    最近更新 更多