【发布时间】:2016-04-16 01:24:19
【问题描述】:
我正在尝试将文件加载到我的程序中,以便我可以单独处理字节,但是当我加载文件时,它会过早地停止加载;总是 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函数中,它不会打印列表中的最后一个元素。 -
您的设计不适用于空文件。它将返回在
val中具有未初始化值的单个节点。 -
有没有报错?
-
不,这没有产生任何错误。它只是提前停止阅读。这是一个可编译的例子。
标签: c file-io linked-list fgetc