【发布时间】:2020-05-04 21:22:40
【问题描述】:
我想从文件的指定偏移值中读取指定数量的字节。我将偏移量、字节数、文件名作为参数传递给文件。下面的代码不起作用。有人可以帮我吗?谢谢。
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<error.h>
#include<errno.h>
#include<fcntl.h>
#define buf_size 512
int main(int argc, char *argv[])
{
int bytes;
int offset;
int fd;
int i = 0;
int length = 0;
ssize_t read_bytes;
char *file;
char buf[buf_size];
if (argc != 4)
error(1, 0, "Too many or less than the number of arguments");
file = argv[1];
offset = atoi(argv[2]);
bytes = atoi(argv[3]);
fd = open(file, O_RDONLY);
if (fd == -1)
error(1, errno, "Error while opening the file\n");
while (1) {
read_bytes = read(fd, buf, bytes);
if (read_bytes == -1)
error(1, errno, "Error while reading the file\n");
length += read_bytes;
printf("The length is : %d\n", length);
if (length >= offset) {
for (i = length ; i < bytes; i++)
putchar(buf[i]);
break;
}
}
if (close(fd) == -1)
error(1, 0, "Error while closing the file\n");
}
【问题讨论】:
-
查找
lseek。 -
另外,想想如果
offset不是bytes的倍数,或者bytes大于buf_size,你的程序会做什么。 -
问题描述“下面的代码不起作用”不是我们可以帮助您的。你的输入是什么?你的代码的输出是什么?你期望从中得到什么输出?请阅读How to Ask。
-
@Tsyvarev 好的,当然。抱歉这个错误。不会再重蹈覆辙。谢谢。
标签: c linux unix operating-system