2012-03-11 141 views
1

我無法從文件讀取特定的整數,我不知道爲什麼。首先,我通讀整個文件以瞭解它有多大,然後將指針重置爲開始。然後我讀取3個16字節的數據塊。然後1個20字節塊,然後我想在最後讀取1個字節作爲整數。但是,我不得不以文字形式寫入文件,但我認爲這不應該成爲問題。我的問題是,當我從文件中讀出它而不是15的整數值時,它是49.我檢查了ACII表,它不是1或5的十六進制或八進制值。我很困惑,因爲我的閱讀聲明是read(inF, pad, 1),我相信是正確的。我知道整數變量是4個字節,但是文件中只剩下一個字節的數據,所以我只讀入最後一個字節。
我的代碼複製功能(它似乎想了很多,但不認爲這是)從C中的文本文件讀取

代碼

#include<math.h> 
#include<stdio.h> 
#include<string.h> 
#include <fcntl.h> 


int main(int argc, char** argv) 
{ 
char x; 
int y; 
int bytes = 0; 
int num = 0; 
int count = 0; 



num = open ("a_file", O_RDONLY); 

bytes = read(num, y, 1); 

printf("y %d\n", y); 

return 0; 
} 

綜上所述,我的問題,如何當我讀到字節來存儲15從文本文件,我不能從整數表示15視圖呢? 任何幫助將不勝感激。 謝謝!

+1

我不能完全瞭解您所用數據做什麼,所以你應該降低代碼的東西簡單,像「從閱讀數一個文件「和」向一個文件寫入一個數字「 - 實驗起來要容易得多。 – che 2012-03-11 23:51:25

+0

@che我將代碼更改爲類似但很簡單的代碼,但我仍然遇到同樣的問題,您有建議嗎? – tpar44 2012-03-12 01:44:00

+1

這是一條線索:49是ASCII字符'1'的十進制值。 – blueshift 2012-03-12 02:01:35

回答

0

基於讀函數,我相信它正在讀取整數的4個字節的第一個字節中的第一個字節,並且該字節不會放在最低字節中。這意味着即使您將其初始化爲零(然後它將在其他字節中具有零),其他3個字節的內容仍然存在。我想讀一個字節,然後將其轉換爲一個整數(如果你需要某種原因,4字節的整數),如下圖所示:

/* declare at the top of the program */ 
char temp; 

/* Note line to replace read(inF,pad,1) */ 
read(inF,&temp,1); 

/* Added to cast the value read in to an integer high order bit may be propagated to make a negative number */ 
pad = (int) temp; 

/* Mask off the high order bits */ 
pad &= 0x000000FF; 

否則,你可以改變你的聲明是一個無符號的字符,其會照顧其他3個字節。

+0

感謝您的幫助!不幸的是,它沒有工作... – tpar44 2012-03-12 01:44:25

+1

'讀(inF,&temp,1);'或者我錯過了什麼? – 2012-03-12 02:06:15

+0

你是對的。我忘了說明函數需要temp的地址。更改了代碼以反映更正。 – Glenn 2012-03-12 05:53:29

0

讀取功能的系統調用具有類似的聲明:

ssize_t read(int fd, void* buf, size_t count); 

所以,你應該通過在你想要閱讀的東西int變量的地址。 即使用

bytes = read(num, &y, 1); 
0

你可以看到C文件I/O的所有細節,從link

1

您正在閱讀INT(4個字節)的第一個字節,然後打印它作爲一個整個。如果你想用一個字節讀,你也需要把它作爲一個字節,這樣的:

char temp; // one-byte signed integer 
read(fd, &temp, 1); // read the integer from file 
printf("%hhd\n", temp); // print one-byte signed integer 

或者,您也可以使用普通的INT:

int temp; // four byte signed integer 
read(fd, &temp, 4); // read it from file 
printf("%d\n", temp); // print four-byte signed integer 

注意,這隻會工作在32位整數平臺上,也取決於平臺的byte order

你在做什麼是:

int temp; // four byte signed integer 
read(fd, &temp, 1); // read one byte from file into the integer 
    // now first byte of four is from the file, 
    // and the other three contain undefined garbage 
printf("%d\n", temp); // print contents of mostly uninitialized memory