read()在c中工作不正常

read()在c中工作不正常,c,io,C,Io,我试图通过使用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)) =

我试图通过使用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);
    }
}
#包括
#包括
#包括
int main(){
char-uselessTable[600];
int-fdInput;
int firstChar;
如果((fdInput=open(“file.txt”,orduonly))=-1){
perror(“文件”);
_出口(1);
}
读取(fdInput和firstChar,1);
printf(“名字Taille du nom de fichier:%d\n”,firstChar);//打印32609
如果(关闭(fdInput)=-1){
perror(“关闭”);
_出口(2);
}
}
该文件包含字符串abc,因此它应该打印数字97,但它不打印,除非我删除表uselessTable,即使它未在该程序中使用


将表的大小更改为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);
}
#包括
#包括
#包括
int main(){
char firstChar=0xff;//强制它,以便您*知道*它会改变。
int fdInput=open(“file.txt”,仅限ordu);
如果(fdInput==-1){
perror(“文件”);
_出口(1);
}
读取(fdInput和firstChar,1);
printf(“名字Taille du nom de fichier:%d\n”,firstChar);//prints 97
关闭(FDI输入);
}

这是因为read()只覆盖firstChar int的第一个字节,导致未定义的行为。将firstChar设置为char,并在对其使用printf()时将其转换为int。将一个字节读入
int
(需要多个字节),其余字节未初始化。