c write file with char * and read file line by line based on FILE

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

void retrieveUuid(char *uuidValue)
{
    uuid_t newUUID;
    uuid_generate(newUUID);
    uuid_unparse(newUUID,uuidValue);
}

void wf5();
void rf6();

int main()
{
    wf5();
    rf6(); 
}

void rf6()
{
    char *msg=(char*)malloc(255);
    FILE *fp=fopen("a.txt","r");
    if(fp==NULL)
    {
        exit(EXIT_FAILURE);
    }
    int num=0;
    while (fgets(msg,255,fp))
    {
        printf("I=%d,value=%s\n",num++,msg);
    }

    fclose(fp);
    if(msg)
    {
        free(msg);
    }    
}

void wf5()
{
    char *msg=(char*)malloc(40);
    FILE *fp=fopen("a.txt","a+");
    if(fp==NULL)
    {
        exit(EXIT_FAILURE);
    }
    for(int i=0;i<10000;i++)
    {
        retrieveUuid(msg);
        strcat(msg,"\n");
        fputs(msg,fp);
    }
    fclose(fp);
    if(msg)
    {
        free(msg);
    }
}

 

 

Read file line by line 

void rf7()
{
    char *msg=(char*)malloc(255);
    FILE *fp=fopen("a.txt","r");
    if(fp==NULL)
    {
        exit(EXIT_FAILURE);
    }
    int num=0;
    size_t len=0;
    while((getline(&msg,&len,fp))!=-1)
    {
        printf("Index=%d,value=%s\n",num++,msg);
    }

    fclose(fp);
    if(msg)
    {
        free(msg);
    }
}

 

posted @ 2021-11-20 17:22  FredGrit  阅读(25)  评论(0编辑  收藏  举报