c - fgetc 无法加载文件的最后一个字符

标签 c file-io linked-list fgetc

我正在尝试将文件加载到我的程序中,以便我可以单独处理字节,但是当我加载文件时,它会过早停止加载;始终按 1 个字符。如果文件中只有一个字符,则不会加载它。是我读取文件的方式有问题还是文件位于不同的位置?

#include <stdio.h>
#include <stdlib.h>

typedef struct node {//linked list structure, I use this because I am working with files of vastly varying length
    char val;
    struct node *next;
} data;

void printdata(data *head);
void freeData(data **head);
data* readFile(FILE *f);

void main(int argc, char *argv[]) {//set this up so it is easier to test
    if(argc == 2) {
        FILE *f = fopen(argv[1], "r");
        data *d = readFile(f);
        fclose(f);
        printdata(d);
        freeData(&d);
    }
}

data* readFile(FILE *f) {//This is the function containing the problem
    data *retVal = malloc(sizeof(data));
    data *cur = retVal;
    int c = fgetc(f);
    if(c != EOF) {
        retVal->val = (char) c;
        while((c = fgetc(f)) != EOF) {
            cur->next = malloc(sizeof(data));
            cur->next->val = (char) c;
            cur = cur->next;
        }
    } else return NULL;//EDIT: was in a rush and forgot to add this.
    cur->next = NULL;
    return retVal;
}

void freeData(data **head) {
    if((*head)->next != NULL) freeData(&((*head)->next));
    free(*head);
}

void printdata(data *head) {
    data *cur = head;
    do {
        printf("%c", cur->val);
        cur = cur->next;
    } while(cur->next != NULL);//EDIT: I changed this because there was a small "problem" that was not the real problem
    printf("\n");
}

最佳答案

printdata() 停止得太快。 @Barmar

cur->next == NULL时不要停止。当 cur == NULL

时停止
void printdata(data *head) {
  data *cur = head;
  while (cur) {
    printf(" <%hhx>", cur->val);  // Changed format for debugging
    fflush(stdout);               // Useful for debugging
    cur = cur->next;
  }
  printf("\n");
}

还包括一个简化的 readFile()

data* readFile(FILE *f) { //This is the function containing the problem
  data head; // Only next field used
  data *cur = &head;
  int c;
  while ((c = fgetc(f)) != EOF) {
      cur->next = malloc(sizeof *(cur->next));
      cur = cur->next;
      assert(cur);
      cur->val = (char) c;
    }
  cur->next = NULL;
  return head.next;
}

关于c - fgetc 无法加载文件的最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36659174/

相关文章:

c - 读取字符 0x1A 时发生文件结尾

c - 帮助理解使用递归反转链表的代码片段

C++ 链表 : Overload bracket operators []

c - 汇编中的内存移动

c - 在 C 中的字符串中添加双引号

c - C 中的宏定义错误?

c# - 在 File.Copy 之后文件正在被另一个进程使用

python - 将一个文件中的特定行写入另一个文件

c - 从文件中读取日语字符的问题 - C

c - c编程中goto的替代方案