0
char x[3];
char buff, c;
x[0]='y';
int offset, i;
int fd;

fd = open("test1.txt", O_RDONLY);
if(fd==-1){ printf("Error on fopen."); exit(1); }

offset = lseek(fd, 1, SEEK_END);
printf("Size of file is: %d. \n", offset);

for(i=offset-1; i>=0; i--)
{
  c = read(fd, &buff, 1);
  printf("The character is: %c. \n", c);
}

close(fd);

これを実行すると、私に与えられます。

Size of file is: 6. 
The character is: . 
The character is: . 
The character is: . 
The character is: . 
The character is: . 
The character is: . 

テスト ファイルには、"TEST" という単語だけが含まれています。単語を逆に印刷できるようにしたい。

4

2 に答える 2

0

はファイルのサイズを返すことが保証されていないためfstat()、ファイル サイズを取得するために使用します。また、 を使用すると、シークをまったく実行することなくファイルを逆方向​​に読み取ることができます。これにはエラー チェックがありません。これは、使用するコードに追加する必要があります。lseek()SEEK_ENDpread()

struct stat sb;
int fd = open("test1.txt", O_RDONLY);
fstat( fd, &sb );
while ( sb.st_size > 0 )
{
    char buff;
    sb.st_size--;
    pread( fd, &buff, sizeof( buff ), sb.st_size );
    printf( "Char read: %c\n", buff );
}
close( fd );
于 2015-09-13T20:56:17.453 に答える