c structured document stream read

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/ming2453755227/article/details/102746976

A structured memory, write the file stream
Method:

#include <stdio.h>
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

Code:

#include <stdio.h>
#include <string.h>
#define set_s(x,y) {strcpy(s[x].name, y); s[x].size = strlen(y);}
#define nmemb 3

struct test{
        char name[20];
        int size;
}s[nmemb];

int main(){
        FILE * fp;
        set_s(0, "LInux!");
        set_s(1, "FreeBSD!");
        set_s(2, "Windows2000");
        fp = fopen("test.txt", "w");
        fwrite(s, sizeof(struct test), nmemb, fp);
        fclose(fp);
        return 0;
}

Output:
[root @ localhost the Test] # vi test.txt
Here Insert Picture Description

Two read from a file, memory structure of
the method:

#include <stdio.h>
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

Code:

#include <stdio.h>

struct test{
        char name[20];
        int size;
};

int main(){
        test arr[3] = {0};
        FILE * fp = fopen("test.txt", "r+");
        fread(arr, sizeof(struct test), 3, fp);

        for(int i = 0;i< 3;i++){
                printf("arr[%d]:name=%s, size=%d\n", i, arr[i].name, arr[i].size);
        }

        fclose(fp);
        return 0;
}

Output:

[root@localhost test]# g++ -o read read.cpp 
[root@localhost test]# ./read 
arr[0]:name=LInux!, size=6
arr[1]:name=FreeBSD!, size=8
arr[2]:name=Windows2000, size=11
[root@localhost test]# 

Guess you like

Origin blog.csdn.net/ming2453755227/article/details/102746976