目录
前言
一、open、read、write、lseek、close函数的初步了解
1.open
2.read
3.write
4.lseek
5.close
二、案例
总结
前言
通过此次课程的学习,我了解到我需要具备如下知识:
计算机网络基础:OSI模型,TCP/IP协议相关知识
C语言与数据结构相关的知识:指针,链表,队列,栈等
Linux环境编程基础:
Code Blocks开发环境的基本使用
程序调试技术
需要掌握如下知识:
文件I/O编程
多线程编程
多进程编程
Socket编程基础
本次课程的主要内容是:文件I/O
一、open、read、write、lseek、close函数的初步了解
这五个函数都是在Linux编程中的对文件进行相关操作的:
1.open
#include
int open(const char *pathname, int flags[, mode_t mode);
2.read
#include
ssize_t read(int fd, void *buf, size_t count);
3.write
#include
ssize_t write(int fd, void *buf, size_t count);
4.lseek
#include
ssize_t write(int fd, off_t offset, int whence);
5.close
#include
int close(int fd);
二、案例
#includessize_t read(int fd, void *buf, size_t count);
3.write
#include
ssize_t write(int fd, void *buf, size_t count);
4.lseek
#include
ssize_t write(int fd, off_t offset, int whence);
5.close
#include
int close(int fd);
二、案例
#includessize_t write(int fd, off_t offset, int whence);
5.close
#include
int close(int fd);
二、案例
课程案例:使用open函数打开或创建一个文件,将文件清空,使用write函数在文件中写入数据,并使用read函数将数据读取并打印。
#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
首先创建代码文件及目标文件,然后使用gcc编译文件:
编译成功后,使用 ./文件名 运行文件:
总结
本次课程让我初步认识了Linux环境下的简单编程。由于之前较少接触Linux编程的缘故,即使本次作业较为简单,但还是出现了不少问题:
1.运行文件需要和代码文件在同一目录下;
2.使用命令界面编译代码文件时,之前的“创建、编写”过程均需要通过命令界面进行创建,这在本次作业的完成过程中给我带来了较大麻烦。



