[英]fgetc fails to load last character of file
我正在嘗試將文件加載到我的程序中,以便我可以單獨處理字節,但是當我加載文件時,它會過早地停止加載; 總是 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()
void printdata(data *head) {
data *cur = head;
while(cur->next != NULL) {
printf("%c", cur->val);
cur = cur->next;
}
printf("\n");
}
請注意,當
cur->next == NULL
while 中的命令將不會被執行。
還要注意,這總是發生在最后一個元素。 所以你的代碼不會打印最后的數據。
在其他解決方案中,您可以使用 do-while 循環:
do{
printf("%c", cur->val)
cur = cur->next;
} while (cur->next != NULL);
這將保證打印最后一個元素,因為 while 將在為最后一個元素執行循環內部之后停止。
希望這可以幫助。
printdata()
停止得太快了。 @巴馬爾
當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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.