我正在在线阅读 GNU C PROGRAMMING TUTORIAL,并且对低级读写的代码示例感到有些困惑。
代码如下:
#include <stdio.h>
#include <fcntl.h>
int main()
{
char my_write_str[] = "1234567890";
char my_read_str[100];
char my_filename[] = "snazzyjazz.txt";
int my_file_descriptor, close_err;
/* Open the file. Clobber it if it exists. */
my_file_descriptor = open (my_filename, O_RDWR | O_CREAT | O_TRUNC);
/* Write 10 bytes of data and make sure it's written */
write (my_file_descriptor, (void *) my_write_str, 10);
fsync (my_file_descriptor);
/* Seek the beginning of the file */
lseek (my_file_descriptor, 0, SEEK_SET);
/* Read 10 bytes of data */
read (my_file_descriptor, (void *) my_read_str, 10);
/* Terminate the data we've read with a null character */
my_read_str[10] = '\0';
printf ("String read = %s.\n", my_read_str);
close (my_file_descriptor);
return 0;
}
我用 gcc 编译代码没有问题。并且第一次运行,也是可以的。输出如下:
$ ./lowLevelWrite
String read = 1234567890.
当我第二次运行程序时出现问题:
$ ./lowLevelWrite
String read = .
似乎代码第二次无法将字符串“1234567890”写入文件。正如我们从 GNU C 手册中知道的那样,O_RDWR | O_CREAT | O_TRUNC
这些标志应该允许我们每次将文件截断为 0,然后写入文件。我不确定为什么第二次执行失败。
任何人都可以帮助我摆脱这种困惑吗?