c - 如何将输入从 read() 转换为 int

标签 c system-calls

我有以下 C 代码:

#include<stdio.h>
#include<unistd.h>
#include <arpa/inet.h>

int main()
{
        uint32_t input;
        read(0, &input, 4);
        printf("%d",input);
        return 0;

}

当我输入 1234 时,我希望它打印 1234 作为返回,但我得到的却是 875770417

如果我有一个不可更改的程序:

#include<stdio.h>
#include<unistd.h>
#include <arpa/inet.h>
int main()
{
        uint32_t a=123;
        uint32_t b=123;
        uint32_t sum=a+b;
        uint32_t input;
        read(0, &input, 4);
        if(sum == input)
                printf("Done\n");
        return 0;

}

如何到达打印语句?因为输入246不行。

最佳答案

875770417 在字面上与 1234 完全相同,如果您将此数字解释为小端字节数的话。下面是一些显示此内容的快速 Python 代码:

>>> (875770417).to_bytes(4, 'little')
b'1234'

The read syscall将读取您输入的原始字节:

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

read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.

您输入了以下字节:

49, 50, 51, 52

...string 1234 的 ASCII 码。

您需要将此字符串转换为整数,但首先将此字符串读入某个缓冲区:

char buffer[64] = {0};
read(0, buffer, 4);

然后使用atoi解析buffer中的字符串并转换为整数:

$ cat test.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
    char buffer[64] = {0};
    uint32_t input;

    read(0, buffer, 4);
    input = atoi(buffer);

    printf("You entered: '%d'\n", input);
}
$ clang test.c && ./a.out
1234
You entered: '1234'
$ 

关于c - 如何将输入从 read() 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61088388/

相关文章:

c - 从缓冲区读取字符

c - malloc 文件中未处理的行

c++ - 在 x64 进程中调用 x86 winapi 函数

java - 了解 ProcessBuilder

c - 汇编的 Linux 系统调用表或速查表

c - 为什么我会收到以下代码的段错误?

c - GTK 文本框编号输入

c - 编译器如何知道您使用的函数是系统调用?

c - 错误地打印链表中的字符串

c - 如何捕获读写系统调用?