0

我编写了以下程序来创建一个包含孔的文件,但在 lseek() 中出现错误,如下所示: lseek <22> 中的错误:无效参数我只想在第 100 位写“1”和“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);
}
4

2 回答 2

4

你交换了论点。

lseek(fd, SEEK_CUR, 100)

应该

lseek(fd, 100, SEEK_CUR)
于 2012-10-17T09:54:32.627 回答
0

rc = write(fd, buff, sizeof(buff));

你有文件末尾的指针,你不能使用 SEEK_CUR,你必须使用 SEEK_SET,你把 lseek 标志放在参数列表中的错误位置:

rc = lseek(fd, 100, SEEK_SET);
于 2012-10-17T09:54:58.867 回答