2012-04-19 108 views
2

我有一個數組正在寫入文件,但是當我調用該函數時,我需要一種方法來從文件中打印出相同的信息。代碼的第一部分位於主函數中,第二部分是第二個函數,用於打印文件中應該有的值(fp)。從文件中的數組寫入和打印字符串C

fp = fopen("Grue.txt", "wb"); 
for(i = 0; i < 5; i++) 
{ 
    char newLine[3] = {"\n"}; 
    char space[2] = {" "}; 
    fwrite(array[i].name, strlen(array[i].name), sizeof(char), fp); 
    fwrite(space, strlen(space), sizeof(char), fp); 
    fwrite(array[i].height, strlen(array[i].height), sizeof(char), fp); 
    fwrite(space, strlen(space), sizeof(char), fp); 
    fwrite(array[i].weight, strlen(array[i].weight), sizeof(char), fp); 
    fwrite(space, strlen(space), sizeof(char), fp); 
    fwrite(array[i].items, strlen(array[i].items), sizeof(char), fp); 
    fwrite(newLine, strlen(newLine), sizeof(char), fp); 
} 
fclose(fp); 
fp = fopen("Grue.txt", "rb"); 
PrintAGrue(fp); 


void PrintAGrue(FILE *a) 
{ 
// create End of file character onto the array being saved, 
int i; 
char n; 
char h; 
char w; 
char m; 

for (i=0; i<5; i++) 
{ 
    n = fread(a[i].name, strlen(array[i].name, sizeof(char), a); 
    h = fread(array[i].height, strlen(array[i].height, sizeof(char), a); 
    w = fread(array[i].weight, strlen(array[i].weight, sizeof(char), a); 
    m = fread(array[i].items, strlen(array[i].items, sizeof(char), a); 

    printf("This grue is called %s and is %s feet tall, and weighs %s pounds, and has eaten %s things.", n, h, w, m); 
} 

}

+1

那麼當你嘗試這個時,它會做什麼? – 2012-04-19 21:47:03

回答

1

PrintAGrue,它看起來像你使用strlen()調用多少來決定要讀取的數據 - 但如何 你能前知道該字符串的大小,你所閱讀? (另外,括號不看平衡...)

也許你的文件格式應明確包括爲每個字符串長度字段 - 那麼你 可以做一個fread找到字符串大小,另一條實際讀取字符串。