linux系统编程——写入一个整数到文件
先要创建file1的文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
int data=100;//设置往文件写入的数字为100
int data2=0;//设置读取文件的内容初始化为0
fd=open("./file1",O_RDWR);//打开file1
int n_write =write(fd,&data,sizeof(int));
//第三个参数是字节的意思,因为写入的是整型数,要把
//整型数在linux环境下占了几个字节数输出出来。
lseek(fd,0,SEEK_SET);
int n_read=read(fd,&data2,sizeof(int));
//往文件写完内容之后,要读取内容
printf("read %d\n",data2);
close(fd);
return 0;
}
当打开file1文件的时候,会出现乱乱的样子,但是并不影响程序对文件写入和操作的影响。
——@上官可编程