#include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<unistd.h> #include<errno.h>

#include<stdio.h> #include<string.h>

#define BUF_SIZE 30

int main(int argc, char* argv[]) { char buf[BUF_SIZE]; int len=0; int fd=-1;

if(argc != 2){ printf('wrong parameters '); return -1; }

fd = open(argv[1], O_RDONLY);

if(fd == -1){ printf('error in open file'); printf('the error is: %s ', strerror(errno)); return -1; }else{ //printf('open file success '); while((len=read(fd, buf, BUF_SIZE))!=0){ write(STDOUT_FILENO, buf, len); } } if(fd>0){ close(fd); } return 0; }

主要修改如下:

  1. 将open函数的flag修改为O_RDONLY,只读打开文件。

  2. 将write函数的第一个参数修改为STDOUT_FILENO,标准输出的文件描述符。

Ubuntu系统下C语言文件读取程序代码优化

原文地址: https://www.cveoy.top/t/topic/nKlR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录