在文件中写入数据
一、 函数原型及头文件
#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);
二、举例
文件源码
int main()
{
int fd;
char *buf = "chao ji shuai\n";
fd = open("./file1", O_RDWR);
if(fd == -1){
printf("open file1 filed\n");
}
fd = open("./file1", O_RDWR|O_CREAT, 0600);
if(fd > 0){
printf("file creat succese\n");
}
write(fd, buf, strlen(buf));
close(fd);
return 0;
}
结果展示
CLC@Embed_Learn:~$ gcc demo3.c
CLC@Embed_Learn:~$ ./a.out
file creat succese
读取文件
头文件及函数原型
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
添加的代码如下
char *readtext;
readtext = (char *)malloc(sizeof(char)*O_WRITE+1);
int O_READ = read(fd, readtext, O_WRITE);
printf("readBuf = %d,context = %s\n",O_READ,readtext);
运行结果
open file1 filed
file creat succese
O_Write: fd = 14
readBuf = 0,context =
此时没有读取到任何数据的原因是写入文件后光标移到了最后一位,在读取时光标不会自动回到第一位从最后一位开始读取,导致读取时没有读到任何数据。
在没有学到光标定位我们可以在写入数据完成后关闭file1文件在打开解决问题。
修改
只需在写入完之后加入
close(fd);
open("./file1",O_RDWR);
运行结果如下
open file1 filed
file creat succese
O_Write: fd = 14
readBuf = 14,context = chao ji shuai
光标移动
头文件及函数原型
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
不用在关闭、打开文件只需在写入操作后加入新的代码有三种实例
1、 SEEK_SET 光标在开头
lseek(fd, 0 , SEEK_SET);
2、向左偏移是负数,向右偏移时是正数,SEEK_CUR表示当前的光标在当前位置;
lseek(fd, -O_WRITE, SEEK_CUR);
3、SEEK_END光标在末尾
lseek(fd, -O_WRITE, SEEK_END);
补充知识
如何计算文件大小
file1的大小为14个字节
lseek函数的返回值为一个整形数
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
fd = open("./file1", O_RDWR);
// off_t lseek(int fd, off_t offset, int whence);
// lseek(fd, 0 , SEEK_SET);
int filesize = lseek(fd, 0, SEEK_END);
printf("filesize = %d\n",filesize);
close(fd);
return 0;
}
三种方法可以尝试一下