Linux下C语言的文件操作
文件的读写
代码
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUFFSIZE 512
#define MSG "hhhh9999"
int main(int main, char * argv[])
{
int fd = -1;
int rv = -1;
char buf[BUFFSIZE] = MSG;
fd = open("text.txt", O_RDWR | O_CREAT | O_TRUNC, 0666);
if(fd<0)
{
perror("opne file error");
return 0;
}
printf("open file return :%d\n",fd);
rv = write(fd, buf, strlen(MSG));
if(rv<0)
{
perror("write file error");
printf("write file error: %s\n",strerror(errno));
goto cleanup;
}
printf("write file %d bytes\n",rv);
//memset(buf, 0, sizeof(buf)); //内存清零
lseek(fd, 0, SEEK_SET);
rv = read(fd, buf,sizeof(buf));
if(rv<0)
{
perror("read file error");
printf("read file error: %s\n",strerror(errno));
goto cleanup;
}
printf("read file %d bytes :%s\n", rv, buf);
cleanup:
close(fd);
return 0;
}
运行结果:
tianyujie@icloud-1st:~$ gcc cp.c
tianyujie@icloud-1st:~$ ./a.out
open file return :3
write file 8 bytes
read file 8 bytes :hhhh9999
tianyujie@icloud-1st:~$
我的错误:
忘记在write时把MSG传给buf,导致text.txt里全是乱码。
prerror()与strerror(errno) 作用一样,都是返回错误。但是strerror(errno)能返回具体错误原因,好用一点。
open()函数可以创建或打开一个文件。
int fd = -1;
fd = open("test.txt", O_RDWR | O_TRUNC | O_CREAT,0666);
第一个参数:文件的绝对路径
第二个参数:函数的具体作用
O_CREAT 如果文件不存在,则创建该文件
O_TRUNC 如果此文件存在,而且为 只写 或 读-写 成功打开,则将其长度截断为0
第三个参数:给文件权限(也可省略)
open的返回值为最小未用文件描述符
write()系统调用,
第一个参数是文集描述符fd,第二个参数是要写的内容,第三个参数是要写的字节数;
此函数是将 buf 里的内容传给 fd 。
read()系统调用,
第一个参数是文集描述符fd,第二个参数是要读的内容,第三个参数是要读的字节数;
此函数是将 fd 的内容传给 buf 。
如果read成功,返回独到的字节数。如果读到文件的尾端,返回 0。
若在到达文档尾端之前有30字节,而要求读100字节,则read返回 30 。下次调用read时,返回 0 。