在本课的学习中,我们主要学习了几个比较基本的操作命令,分别为是open,read,write,lseek,close
作用分别是打开文件,读取文件,对文件进行编写,指向文件,关闭文件。
返回值分别为
- 调用成功,返回一个文件描述符
- 不成功,返回-1
ssize_t: 有符号的size_t,有三种返回值
– 正数:请求读取的字节数
– 0: 文件长度有限,若读写位置距文件末尾只有20字节,该函数请求读取30字节,则第一次读取时返回值为20,第二次读取时,返回0
– -1: 读取文件出错
返回写入的字节数或者-1并设置errno
- 设置成功:返回新的偏移量
- 不成功:-1
- 成功:返回0
- 不成功:-1
在案例中只要是对文件进行打开,编写,关闭操作。
#include#include #include #include #include int main(){ int tempFd = 0; char tempFileName[20] = "test.txt"; //Step 1. open the file. tempFd = open(tempFileName, O_RDWR|O_EXCL|O_TRUNC, S_IRWXG); if(tempFd == -1){ perror("file open error.n"); exit(-1); }//of if //Step 2. write the data. int tempLen = 0; char tempBuf[100] = {0}; scanf("%s", tempBuf); tempLen = strlen(tempBuf); write(tempFd, tempBuf, tempLen); close(tempFd); //Step 3. read the file 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
在学过本门课之后,对这些操作有了更加清晰与深刻的认知。但是由于VMware试用期结束了,暂时没有找到密匙,所以没有在课后进行,但是在课上已经基本完成了操作。



