2012-03-11 142 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