利用open(), read()函数编写一个读取文件夹poetry中的任意文件,一次读取10字节,然后休眠1秒钟,并且显示出来。 将读取文件的操作放入函数ReadPotery()函数中。c语言
时间: 2023-11-28 12:48:54 浏览: 28
以下是利用open(), read()函数编写的读取文件夹poetry中的任意文件,一次读取10字节,然后休眠1秒钟,并显示出来的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
void ReadPoetry(char *filename) {
int fd;
char buf[11]; // 10字节数据加上'\0'
ssize_t len;
fd = open(filename, O_RDONLY);
if (fd == -1) {
printf("Open file %s failed!\n", filename);
return;
}
while ((len = read(fd, buf, 10)) > 0) {
buf[len] = '\0';
printf("%s", buf);
sleep(1);
}
printf("\n");
close(fd);
}
int main() {
ReadPoetry("poetry/1.txt");
return 0;
}
```
在该代码中,我们定义了一个函数ReadPoetry(),它接收文件名作为输入参数。该函数首先打开文件,并在文件读取的同时,每次读取10个字节,然后休眠1秒钟并显示出来。最后,关闭文件描述符。
在主函数中,我们调用ReadPoetry()函数,并传入参数"poetry/1.txt",即可读取该文件夹下的1.txt文件。