gpt4 book ai didi

c - read() 在 c 中无法正常工作

转载 作者:行者123 更新时间:2023-11-30 19:11:31 24 4
gpt4 key购买 nike

我正在尝试使用 unistd 的读取函数来获取文件中第一个字符的值,但我遇到了奇怪的行为问题:

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

int main() {
char uselessTable[600];
int fdInput;
int firstChar;

if ((fdInput = open("file.txt", O_RDONLY)) == -1) {
perror("file");
_exit(1);
}

read(fdInput, &firstChar, 1);
printf("Taille du nom de fichier : %d\n", firstChar); // prints 32609

if (close(fdInput) == -1) {
perror("close");
_exit(2);
}
}

该文件包含字符串 abc,因此它应该打印数字 97,但事实并非如此,除非我删除了表 UnusableTable,即使该程序中未使用该表。

将表的大小更改为 500、删除它、在firstChar 之后创建它或将 int firstChar 更改为 char firstChar 似乎可以解决问题,但我不明白为什么。

最佳答案

让我们逐步完成这个过程。首先,创建一个局部变量 firstChar,它是一个 int 而不是 char。未初始化的局部变量(并且不是静态)可以设置为任意值。

为了简单起见,我们会说 int 数据类型实际上是四个字节长。

下一步是将一个单个 char 变量读入该四字节int 的地址中。所以你最终得到的是内存:

           +-----+-----+-----+-----+
firstChar: | 'a' | ? | ? | ? |
+-----+-----+-----+-----+

int 的第一个字节设置为 97(假设为 ASCII),其他字节仍设置为某个任意值。

由于整数由所有四个字节组成,因此您会得到类似32609的内容。

显而易见的解决方案是使用 char 变量,该变量仅使用一个字节。这样,当您覆盖该字节时,它将完全代表您读入的内容:

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

int main() {
char firstChar = 0xff; // force it so you *know* it changes.
int fdInput = open("file.txt", O_RDONLY);
if (fdInput == -1) {
perror("file");
_exit(1);
}

read(fdInput, &firstChar, 1);
printf("Taille du nom de fichier : %d\n", firstChar); // prints 97

close(fdInput);
}

关于c - read() 在 c 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39935339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com