2012-10-28 53 views
0

我遇到了使用stdio命令操縱文件中的數據的問題。簡而言之,當我將數據寫入一個文件時,write會返回一個int值,表示它是成功的,但是當我讀取它時,我只能得到舊數據。從寫入stdio數據沒有將其寫入文件

下面的代碼的精簡版:

fd = open(filename,O_RDWR|O_APPEND); 

struct dE *cDE = malloc(sizeof(struct dE)); 

//Read present data 
printf("\nreading values at %d\n",off); 
printf("SeekStatus <%d>\n",lseek(fd,off,SEEK_SET)); 
printf("ReadStatus <%d>\n",read(fd,cDE,deSize)); 

printf("current Key/Data <%d/%s>\n",cDE->key,cDE->data); 

printf("\nwriting new values\n"); 
//Change the values locally 
cDE->key = //something new 
cDE->data = //something new 

//Write them back 
printf("SeekStatus <%d>\n",lseek(fd,off,SEEK_SET)); 
printf("WriteStatus <%d>\n",write(fd,cDE,deSize)); 

//Re-read to make sure that it got written back 
printf("\nre-reading values at %d\n",off); 
printf("SeekStatus <%d>\n",lseek(fd,off,SEEK_SET)); 
printf("ReadStatus <%d>\n",read(fd,cDE,deSize)); 

printf("current Key/Data <%d/%s>\n",cDE->key,cDE->data); 

此外,這裏的德結構的情況下,你想知道:

struct dE { 
    int key; 
    char data[DataSize]; 
}; 

此打印:

reading values at 1072 
SeekStatus <1072> 
ReadStatus <32> 
current Key/Data <27/old> 

writing new values 
SeekStatus <1072> 
WriteStatus <32> 

re-reading values at 1072 
SeekStatus <1072> 
ReadStatus <32> 
current Key/Data <27/old> 
+0

是否讀取((* fd).fd,cDE,deSize);'乾淨地編譯?此外,解引用指針使用' - >',即'cDE-> key'。 –

+1

你從不設置變量'offset'和'deSize'的值,所以它們可能是任何東西。您從不檢查'read','write'或'lseek'的返回值。您需要發佈代碼的條形編譯版本,以說明您遇到的問題或您要問的問題。 90%的時間,創建可編譯示例的練習將爲您解答問題。 –

+0

你對目錄和文件有權限嗎? – cowboydan

回答

1

open呼叫中刪除|O_APPEND

+0

這樣做!這是一個巨大的疏忽......從'man 2 open',在'O_APPEND'下:「在每次寫入(2)之前,文件偏移位於文件的末尾,就像使用lseek(2)」 – darkpbj