c - 如何使用 C 中的 read() 函数读取整数和字符?

标签 c io

我正在 Linux 上工作,我有一个文件包含这样的行:

328abc

我想在 C 语言中仅使用以下函数读取整数部分 (328) 和字符“a”、“b”、“c”:

ssize_t read (int filedes, void *buffer, size_t size))

这是该文件包含的唯一内容。 我知道有更好的方法可以使用其他函数来做到这一点,但我已经很长时间没有用 C 编写代码了,并且试图帮助 friend ,只有这个函数是允许的。 我该如何使用缓冲区来做到这一点? 谢谢

编辑: 我知道我需要手动解析缓冲区。我的问题是如何?

最佳答案

如果这是文件中唯一的内容。这会做:

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

int main() {
    char buffer[6];
    char intBuffer[4];
    ssize_t bytesRead;

    int number;
    int fd;

    if ((fd = open("file.txt", O_RDONLY)) == -1) {
        perror("Error opening file");
        exit(EXIT_FAILURE);
    }

    if ((bytesRead = read(fd, buffer, 6)) == -1) {
        perror("Error reading file");
        exit(EXIT_FAILURE);
    }

    memcpy(intBuffer, buffer, 3);
    intBuffer[3] = '\0';

    number = atoi(intBuffer);
    printf("The number is %d\n", number);

    exit(EXIT_SUCCESS);
}

以下代码将打印“The number is 328”。

关于c - 如何使用 C 中的 read() 函数读取整数和字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32717269/

相关文章:

javascript - 开源钛开发者的源代码藏在哪里?

c - C 中的 LRU 缓存设计,大小有限

haskell - IO 是免费的 Monad 吗?

c# - 如何在 C# 中强制解锁文件?

python - 将每个质数写在不同的行中(Python 3)

c - 在 C 中写入文件时减少磁盘访问次数

c - Linux 帧缓冲驱动程序和自定义文件操作

c - 结构体作为外部函数 C 的参数

haskell - 无限循环与IO如何在haskell中工作

使用命令提示符和 C 检查网络上的计算机状态