lseek()
必要なサイズのファイルを作成しながら、の使用を真に理解しようとしています。そこで、input で指定されたサイズのファイルを作成することを唯一の目的とするこのコードを書きました。
たとえば、次のように実行します。
$ ./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;
}