我试图lseek()
在创建所需大小的文件时真正理解使用。所以我编写了这段代码,其唯一目标是创建一个输入中给定大小的文件。
运行例如:
$ ./lseek_test myFile 5
我希望它创建一个名为myFile
5 个字节的文件,其最后一个字节被数字 5 占据。我得到的是一个我什至无法访问的文件。怎么了?我是否错误地解释了lseek()
用法?
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#define abort_on_error(cond, msg) do {\
if(cond) {\
int _e = errno;\
fprintf(stderr, "%s (%d)\n", msg, _e);\
exit(EXIT_FAILURE);\
}\
} while(0)
/* Write an integer with error control on the file */
void write_int(int fd, int v) {
ssize_t c = write(fd, &v, sizeof(v));
if (c == sizeof(v))
return;
abort_on_error(c == -1 && errno != EINTR, "Error writing the output file");
abort_on_error(1, "Write operation interrupted, aborting");
}
int main(int argc, char *argv[]) {
// Usage control
abort_on_error(argc != 3, "Usage: ./lseek_test <FileName> <FileSize>");
// Parsing of the input
int size = strtol(argv[2], NULL, 0);
// Open file
int fd = open(argv[1], O_RDWR|O_CREAT, 0644);
abort_on_error(fd == -1, "Error opening or creating file");
// Use lseek() and write() to create the file of the needed size
abort_on_error(lseek(fd, size, SEEK_SET) == -1, "Error in lseek");
write_int(fd, size); // To truly extend the file
//Close file
abort_on_error(close(fd) == -1, "Error closing file");
return EXIT_SUCCESS;
}