今天主要是进行了代码的编写:有关Linux下的文件创建,关闭,读写函数简单应用
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<errno.h>
#include<unistd.h>
//在调用系统函数时一定要做异常检测!!!
int main(int argc,char *argv[])
{
// int ret;
int fd;
if(argc != 2)
{
printf("please input file name!\n");
exit(1);
}
// ret = creat(argv[1],S_IRUSR | S_IWUSR); //argv[1]:char * //创建文件函数
// fd = creat(argv[1],0655); //errno
//yi chang chu li
//method 1
/*
* if(fd == -1)
{
if(errno == EISDIR)
{
printf("file name is dir\n");
exit(1);
}
}
*/
//method 2
/* if(fd == -1)
{
perror("creat file is failed!");
exit(1);
}
printf("creat success:%d\n",fd);
*/
if((fd = open(argv[1], O_RDWR | O_CREAT, 0655)) < 0) //打开文件函数
{
perror("open file is failed!");
exit(1);
}
else
{
printf("open file success!:%d\n",fd);
}
char buf[1024] = "hello world";
int w_len;
w_len = write(fd,buf,strlen(buf)); //写函数
if(w_len < 0)
{
perror("write error!");
exit(1);
}
else
{
printf("write data len is %d\n",w_len);
}
memset(buf,0,sizeof(buf)); //清空buf缓存区内容
lseek(fd, 0, SEEK_SET); //将文件读写头移动到文件开始位置
int r_len;
r_len = read(fd,buf,sizeof(buf)); //读函数
if(r_len < 0)
{
perror("read failed!");
exit(1);
}
else
{
printf("read date len is %d\n",r_len);
}
buf[r_len] = '\0';
printf("read data is %s\n",buf);
/*
* char temp = 'H';
write(fd,buf,strlen(buf));
write(fd,&temp,1);
temp = 5 + '0';
write(fd,&temp,1);
*/
close(fd); //关闭文件,也很重要
return 0;
}