我想加載一個文件到我的程序中,這樣我就可以在單個基礎上處理字節,但是當我加載文件時,它會提前停止加載;總是由1個字符組成。如果文件中只有一個字符,則不會加載它。我是如何閱讀文件的問題,還是在不同的位置?fgetc無法加載文件的最後一個字符
#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
您的設計對空文件無法正常工作。它會返回一個單獨的節點,該節點在'val'中有一個未初始化的值。 – Barmar
它是否產生任何錯誤? –