我编写了以下程序来创建一个包含孔的文件,但是我在lseek()中收到错误,如下所示: lseek< 22>中的错误: 无效的论点 我只想先写“1”,第100次写“2”。我也尝试了SEEK_END,但没有成功
#include<stdio.h>
#include<errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main(void) {
int fd = -1;
int rc = -1;
char *buff = "1";
char *buff_end = "2";
char *err;
fd = open("hole_file", O_CREAT | O_RDWR | O_TRUNC, 0644);
if (fd == -1) {
printf("\n Error in open() !!!");
return (-1);
}
rc = write(fd, buff, sizeof(buff));
if (rc == -1) {
printf("\n Error in writing at start location <%d>", errno);
close(fd);
unlink("hole_file");
return (-1);
}
rc = lseek(fd, SEEK_CUR, 100);
if (rc == -1) {
err = strerror(errno);
printf("\n Error in lseek <%d> : %s\n", errno, err);
close(fd);
unlink("hole_file");
return (-1);
}
rc = write(fd, buff_end, sizeof(buff_end));
if (rc == -1) {
printf("\n Error in writing at 100th offset <%d>", errno);
close(fd);
unlink("hole_file");
return (-1);
}
close(fd);
return (0);
}
答案 0 :(得分:4)
你已经交换了论据。
lseek(fd, SEEK_CUR, 100)
应该是
lseek(fd, 100, SEEK_CUR)
答案 1 :(得分:0)
在
rc = write(fd, buff, sizeof(buff));
你有指针在文件的末尾,你不能使用SEEK_CUR,你必须使用SEEK_SET,并将lseek标志放在参数列表中的错误位置:
rc = lseek(fd, 100, SEEK_SET);