lseekを使用してファイルに穴をあける方法を学んでいます。
これは私がこれまでに書いたコードです...
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
int main()
{
int fd;
char name[20] = "Harry Potter";
// Creating a file
if( (fd = open( "book.txt", O_RDWR | O_CREAT , S_IWRITE | S_IREAD ) < 0 )) {
printf("\ncreat error");
}
// Seeking 100th byte, from the begining of the file
if ( lseek(fd, 100, SEEK_SET) == -1 ) {
if (errno != 0) {
perror("lseek");
}
}
// Writing to the 100th byte, thereby creating a hole
if( write(fd, name, sizeof(char)*strlen(name)) != sizeof(char)*strlen(name) ) {
if (errno != 0) {
perror("write");
}
}
// closing the file
if ( close(fd) == -1 ) {
if (errno != 0)
perror("close");
}
return 0;
}
このコードをコンパイルして実行すると、lseek エラーが発生し、「Harry Potter」という名前がファイルに挿入されません。これは、上記のコードを実行したときの出力です。
lseek: Illegal seek
Harry Potter
私はすべてのエラーをキャッチしようとさえしています。さらに助けてください。