1

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

私はすべてのエラーをキャッチしようとさえしています。さらに助けてください。

4

1 に答える 1

3
if( (fd = open( "book.txt", O_RDWR | O_CREAT , S_IWRITE | S_IREAD ) < 0 )) {

これにより、オープンが成功した場合は fd が 0 に設定され、失敗した場合は 1 に設定されます。コンソールである0に設定したため、ディスクではなく、「ハリー・ポッター」が書き込まれた場所です。また、端末では lseek できません。あなたがしたい

if( (fd = open( "book.txt", O_RDWR | O_CREAT , S_IWRITE | S_IREAD )) < 0 ) {

また

a) システムコールが失敗した後に errno != 0 であることを確認する必要はありません。

b) 失敗するのではなく、エラーが発生したときに終了する必要があります。

c) sizeof(char) は常に 1 なので、それを掛ける必要はありません。

d) main にはプロトタイプが必要です。たとえば、int main(void)

于 2014-08-14T11:17:06.457 に答える