Linux c语言操作入门文件编程之C库API

Linux c语言操作入门文件编程之C库API

在linux环境下对文件进行操作时,使用到open、read、write、sleek和close均为UNIX系统调用函数(包括LINUX等),C语言库中也有对应的函数API:fopen、fread、fwrite、fsleek和fclose
两者的差异之处可参考总结open与fopen的区别

c库API使用实例

以下是使用C库API进行字符串数据写入的实例记录,不同数据类型的使用与前文流程一致

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    
    
//      FILE *fopen(const char *path, const char *mode);
        FILE *fp;
        char *str="xxxxxx";

        fp=fopen("./test.txt","w+");

//size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
//size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
//      fwrite(str,sizeof(char),strlen(str),fp);
        int w_n=fwrite(str,sizeof(char)*strlen(str),1,fp);

        char *readbuf=NULL;

        fseek(fp,0,SEEK_SET);

        readbuf=(char *)malloc(sizeof(char)*strlen(str)+8);

        int r_n=fread(readbuf,sizeof(char),strlen(str),fp);
// int fseek(FILE *stream, long offset, int whence);

        fclose(fd);
        return 0;
}

fputcfgetcfeof

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    
    
        FILE *fd;
        char *data="asdfghj";

        fd=fopen("./test.txt","w+");
        int len=strlen(data);

        for(int i=0;i<len;i++)
        {
    
    
                fputc(*data,fd);
                data=data+1;
        }

        fclose(fd);
        fd=fopen("./test.txt","r");
        char c;
        while(!feof(fd))
        {
    
    
                 c=fgetc(fd);
                printf("%c",c);
        }

        fclose(fd);
        return 0;
}

猜你喜欢

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