要求我们进行linux文件的操作,通过C语言来进行文件的操作。
通过这节课,我学习到了一些c语言中关于文件按操作的函数。例如open(),read(),write(),lseek(),close()。
一:open()函数:打开或创建一个文件,该函数存在于系统函数库fcntl.h
其函数声明如下:
#include
int open(const char *pathname, int flags[, mode_t mode);
二:read()函数:用于从已打开的设备或文件中读取数据,存在于函数库unistd.h
其函数声明如下:
#include
ssize_t read(int fd, void *buf, size_t count);
三:close()函数:用于关闭文件,在函数库unistd.h
其函数说明如下:
#include
int close(int fd);
成功:返回0
不成功:-1
四:write()函数:用于向已打开的设备或文件中写入数据,存在于函数库unistd.h
其函数说明如下:
#include
ssize_t write(int fd, void *buf, size_t count);
五:lseek()函数:每个打开的文件都有一个偏移量,该值为非负整数,表示文件的读写位置,linux通过调用lseek()对数值进行修改,存在于函数库unistd.h
其函数说明如下:
#include
ssize_t write(int fd, off_t offset, int whence);
seek函数参数说明:
fd: 从open或create函数返回的文件描述符
offset: 对文件偏移量的设置,参数可正可负.
#include#include #include #include #include int main(){ int tempFd = 0; char tempFileName[20] = "wangzihan.txt"; tempFd = open(tempFileName, O_RDWR|O_EXCL|O_TRUNC, S_IRWXG); if(tempFd == -1){ perror("file open error.n"); exit(-1); }//of if int tempLen = 0; char tempBuf[100] = {0}; scanf("%s", tempBuf); tempLen = strlen(tempBuf); write(tempFd, tempBuf, tempLen); close(tempFd); tempFd = open(tempFileName, O_RDONLY); if(tempFd == -1){ perror("file open error.n"); exit(-1); }//of if off_t tempFileSize = 0; tempFileSize = lseek(tempFd, 0, SEEK_END); lseek(tempFd, 0, SEEK_SET); while(lseek(tempFd, 0, SEEK_CUR)!= tempFileSize){ read(tempFd, tempBuf, 1024); printf("%sn", tempBuf); }//of while close(tempFd); return 0; }//of main
运行截图
心得体会
1.通过本次学习,我学到了c语言对于文件操作的几种常用方法,也熟悉了Linux环境下的程序编写流程,同时通过观察老师的代码我也理解了编写过程中格式规范的重要性,只有拥有完备注释与格式的代码才可以进行正常的维护调试,在今后的学习工作中我将瑾记今天学到的内容,通过不断的积累提升自己。



