Linux c语言操作入门文件编程之不同类型数据的写入

Linux c语言操作入门文件编程之不同类型数据的写入

  • 以字符串的形式写入时,文件打开可直观观察到内容,但其它数据类型写入后直接打开文件会出现乱码到情况,但读取使用正常。

1.整形数的写入

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>


int main()
{
    
    
        int fd;
        char buf[]="xxxxxxxxxxxxxxxxxxxxx";
        int data=100;
        fd=open("./file1",O_RDWR);

        if(fd==-1)//如果没有则创建
        {
    
    
                printf("fail to open this file1!!!\n");
                fd=open("./file1",O_RDWR|O_CREAT,0600);
                {
    
    
                        printf("successful creat file1!!n");
                }

        }

        printf("open success fd=%d!!!!\n",fd);

        int num_write=write(fd,&data,sizeof(data));//返回写入到字符个数

        if(num_write!=-1)
        {
    
    
                printf("write success!!!\n");
        }

        close(fd);//关闭当前文档
        fd=open("./file1",O_RDWR);//重新打开该文档,光标定位开头
        int *readBuf;
        readBuf=(int*)malloc(sizeof(int)*num_write+1);

        int num_read=read(fd,readBuf,num_write);
        printf("read:%d\n",*readBuf);
        close(fd);
        return 0;
}

2.结构体数组的写入

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>


struct Name
{
    
    
        char N;
        int data;
};


int main()
{
    
    
        int fd;
        char buf[]="xxxxxxxxxxxxxxxxxxxxx";
        int data=100;
        struct Name Ren[2]={
    
    {
    
    'a',100},{
    
    'b',200}};
        struct Name RenRead[2];

        fd=open("./file1",O_RDWR);

        if(fd==-1)//如果没有则创建
        {
    
    
                printf("fail to open this file1!!!\n");
                fd=open("./file1",O_RDWR|O_CREAT,0600);
                {
    
    
                        printf("successful creat file1!!n");
                }

        }

        printf("open success fd=%d!!!!\n",fd);

        int num_write=write(fd,&Ren,sizeof(Ren));//返回写入到字符个数

        if(num_write!=-1)
        {
    
    
                printf("write success!!!\n");
        }
        
        close(fd);//关闭当前文档
        fd=open("./file1",O_RDWR);//重新打开该文档,光标定位开头

        int num_read=read(fd,RenRead,num_write);
        printf("read:%c\n",RenRead[0].N);
        printf("read:%d\n",RenRead[0].data);
        close(fd);
        return 0;
}

猜你喜欢

转载自blog.csdn.net/ONERYJHHH/article/details/126256594