类unix环境编程中,一切都是文件,所以想在linux环境下编程,懂得文件编程是必须的。
文件读写无非读,写,重定位。今天就讨论下文件的读写和重定位。
对内核而言,打开的文件都由文件描述符描述。当创建一个文件或者打开一个现有的文件的时候,内核像进程返回一个文件描述符。 使用open和close返回的文件描述符,可以作为参数传递给read和write。在posix系统中,用STDIN_FILENO,STDERR_FILENO表示标准输入,输出,错误。
open函数:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
int creat(const char *pathname, mode_t mode);
参数:
1.const char *pathname,文件路径
2.flag,文件的打开模式。文件打开模式有很多。可以通过或的模式来构成flag,但是O_RDONLY,O_WRONLY,O_RDWR,O_EXEC,O_SEARCH这几个参数只能选一个。
3.权限模式。
返回值:文件描述符。
lseek函数:
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
参数:
1.fd,文件描述符。
2.offset,定位偏移量
3.whence,从哪个地方开始便宜offset字节。
返回值:
重定位后的文件偏移量。如果失败返回-1。
write函数:
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
write函数表示向指定文件描述符,写入count个字符。
参数:
1.fd,文件描述符
2.buf,写入文件的数据源
3.count,写入的字符数。
返回值:
写入的字节数,如果失败返回-1。
read函数:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
read函数从指定文件描述符读取count个字节到buf。
参数:
1.fd,文件描述符
2.buf,读取内容的缓存位置。
3.count,要读取的字节数。
返回值:
如果读取成功则返回读取的字节数,失败返回-1。
写一个deamon
#include <fcntl.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
using namespace std;
int main(int argc, char**argv)
{
int fd = 0;
int len = 0;
off_t offset = 0;
char buff[256] = {'0'};
int readLen = 0;
fd = open("./test.txt", O_RDWR | O_CREAT | O_APPEND);
cout<<"open file description:%d"<<fd<<endl;
for(int i = 0; i<argc; i++)
{
len = write(fd, " ", 1);
cout<<"write len:"<<len<<endl;
len = write(fd, argv[i], strlen(argv[i]));
cout<<"write len:"<<len<<endl;
}
//设置文件偏移量为从文件开头后的20字节,
//假如偏移量设置的值超过了文件尾部,则再读该文件返回0
offset = lseek(fd, 5, SEEK_SET);
cout<<"offset: "<<offset<<endl;
readLen = read(fd, buff, 100);//假如要读取的字符数目大于从文件seek处到文件尾部的位置,则读到文件尾部。
cout<<"read length:"<<readLen<<endl;
cout<<buff<<endl;
//当前文件偏移量已经到达文件尾部,再调用read读取文件,则返回0,传入的buff不受影响
readLen = read(fd, buff, 100);
cout<<"read length:"<<readLen<<endl;
cout<<buff<<endl;
close(fd);
return 0;
}
../obj/unix_program.o hello world
执行结果:
open file description:%d3
write len:1
write len:21
write len:1
write len:5
write len:1
write len:5
offset: 5
read length:29
bj/unix_program.o hello world
read length:0
bj/unix_program.o hello world
makefile文件写法也在持续学习中。
unix_program.o : unix_program_io.cpp
g++ -o unix_program.o unix_program_io.cpp
mv *.o ../obj
clean:
rm ../obj/*.o