[英]How to read an integer and a char with read() function in C?
我在linux上工作,我有一个文件,其中包含这样的行:
328abc
我想在C语言中,仅使用以下函数读取整数部分(328)和字符'a','b','c':
ssize_t read (int filedes, void *buffer, size_t size))
这是文件包含的唯一内容。 我知道有更好的方法可以使用其他功能,但是我已经很长时间没有用C编写代码了,并且试图帮助一个朋友,只允许使用此功能。 我该如何使用缓冲器来做到这一点? 谢谢
编辑:我了解我需要手动解析缓冲区。 我的问题是如何?
如果那是文件中唯一的内容。 这样可以:
#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);
}
下面的代码将打印“数字为328”。
这是某种作业吗?
我问是因为有比使用read
函数更好的方法了。
无论如何回答您的问题, read
从文件描述符为filedes
的文件中读取size
字节,并将其放入buffer
。
它对换行符等一无所知。因此,您需要手动查找行的结尾等。如果只想使用read,则需要在每次read
调用之后手动解析缓冲区(假设您的文件包含许多行,您要解析)。
请注意,可能在两个read
调用之间分配了一行,因此您必须谨慎处理这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.