【问题标题】:Reading from a text file in C从 C 中的文本文件中读取
【发布时间】:2012-03-11 23:42:58
【问题描述】:

我在从文件中读取特定整数时遇到问题,我不知道为什么。首先,我通读了整个文件以了解它有多大,然后我将指针重置为开头。然后我读取了 3 个 16 字节的数据块。然后是 1 个 20 字节的块,然后我想在最后读取 1 个字节作为整数。但是,我必须作为字符写入文件,但我认为这不应该是一个问题。我的问题是,当我从文件中读取它而不是 15 的整数值时,它是 49。我检查了 ACII 表,它不是 1 或 5 的十六进制或八进制值。我非常困惑,因为我的阅读声明是read(inF, pad, 1),我认为这是正确的。我确实知道一个整数变量是 4 个字节,但是文件中只剩下一个字节的数据,所以我只读取了最后一个字节。
我的代码是复现了这个功能(貌似很多但没想到是这样)

代码是

#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? 任何帮助将不胜感激。 谢谢!

【问题讨论】:

  • 我不太清楚您对数据做了什么,因此您可能应该将代码简化为更简单的代码,例如“从文件中读取数字”和“将数字写入一个文件”——试验起来要容易得多。
  • @che 我把代码改成了类似但非常简单的代码,但我仍然遇到同样的问题,你有什么建议吗?
  • 这里有个线索:49是ASCII字符'1'的十进制值。

标签: c file pointers byte ascii


【解决方案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

【讨论】:

    【解决方案2】:

    读取函数系统调用的声明如下:

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

    因此,您应该传递要在其中读取内容的 int 变量的地址。 即使用

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

    【讨论】:

      【解决方案3】:

      你可以从link看到C中文件I/O的所有细节

      【讨论】:

        【解决方案4】:

        基于读取函数,我相信它是读取整数的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;
        

        否则,您可以将声明更改为 unsigned char 来处理其他 3 个字节。

        【讨论】:

        • 你是对的。我忘了指出函数需要临时地址。更改了代码以反映更正。
        猜你喜欢
        • 2020-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多