我正在 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/