Write and Reread a text file, 2 ways.

A sample about writing a text file in C, reread it, using two methods.

fscanf,fgets

See version :

Pas de dépendances

Download :

#include <stdio.h>

void ecriture1()
{
    FILE* F;
    int a,b;
    double d;
    char* chaine = "plouf";
    printf("-- ecriture1\n");
    F = fopen("test.txt","w");
    a = 5;
    b = 6;
    d = 5.3;
    fprintf(F,"%d %f %d\n",a,d,b);
    fprintf(F,"%s\n",chaine);
    fclose(F);
}

void lecture1()
{
    FILE* F;
    int a;
    int b;
    double d;
    char chaine[500];
    printf("-- lecture1\n");
    F = fopen("test.txt","r");
    fscanf(F,"%d",&a);
    fscanf(F,"%lf",&d);
    fscanf(F,"%d",&b);
    fscanf(F,"%s",chaine);
    printf("%d %f %d %s\n",a,d,b,chaine);
    fclose(F);
}

void lecture2()
{
    FILE* F;
    char buf[1000];
    printf("-- lecture2\n");
    F = fopen("test.txt","r");
    while(!feof(F))
    {
        buf[0] = '\0';
        fgets(buf,1000,F);
        printf("%s",buf);
    }
    fclose(F);
}

int main()
{
    ecriture1();    
    lecture1();    
    lecture2();
    return 0;
}



Explanations

	No explanations yet.