C program to write environment variables and their values into file and read the variables and their values from the file (using strtok)

C program to write environment variables and their values into file and read the variables and their values from the file (using strtok)


Neelkanth_39$ cat neel.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

void func_read();
void func_write(char **envp);

void func_write(char **envp)
{

    FILE *fp = NULL;
    char a[1000];
    int i = 0;
    int len = 0;

    printf("\n WRITING ENVIRONMENT VARIABLES INTO FILE \n");
    fp = fopen ("file.txt", "w");
    if (fp == NULL){
        printf("failed to open %s", "file.txt");
        return ;
    }


    while(envp[i] != NULL) {
          strcat(a , envp[i]);
          strcat(a , "@");
          i++;
    }
    printf("%s\n",a);
    len = strlen(a);

    a[len+1] = '\0';

    fwrite( a, strlen(a), 1, fp);
    fclose(fp);

    func_read();

}

void func_read()
{
    char **envp;
    char a[1000];
    FILE *fp;
    char *pt;
    char temp[10][100];
    int i = 0;

    printf("\n READING ENVIRONMENT VARIABLES AND THEIR VALUES FROM FILE \n");
    fp = fopen ("file.txt", "r");
    if (fp == NULL) {
        printf("failed to open %s", "file.txt");
        return ;
    }

    fscanf(fp, "%s", a);

    pt = strtok (a,"@");
    while (pt != NULL) {
        printf("%s\n", pt);
        strcpy(temp[i], pt);
        pt = strtok (NULL, "@");
        i++;
    }
    printf("temp[0]: %s\n", temp[0]);
    printf("temp[1]: %s\n", temp[1]);
    printf("temp[2]: %s\n", temp[2]);

    char *name, *value;

    name = strtok(temp[0], "=");
    printf("name: %s\n", name);
    value = strtok(NULL, "=");
    printf("value: %s\n", value);

    return;

}

int main()
{

    char *envp[] = {"stallone=rambo" ,"google=god", "hrithik=me", NULL };

    printf("\n PASS ENVIRONMENT VARIABLES TO WRITE TO FILE FUNCTION \n");
    func_write(&envp[0]);

    return 0;
}




Output:


Neelkanth_39$ gcc neel.c
Neelkanth_39$ ./a.out

 PASS ENVIRONMENT VARIABLES TO WRITE TO FILE FUNCTION

 WRITING ENVIRONMENT VARIABLES INTO FILE
stallone=rambo@google=god@hrithik=me@

 READING ENVIRONMENT VARIABLES AND THEIR VALUES FROM FILE
stallone=rambo
google=god
hrithik=me
temp[0]: stallone=rambo
temp[1]: google=god
temp[2]: hrithik=me
name: stallone