1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| #include <stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
void creer_fichier(int nb_ligne)
{
int T;
int i;
int m=0;
char buff[4];
if( (T=open("Fichier_test",O_CREAT | O_WRONLY | O_TRUNC , S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
{
printf("Erreur\n");
exit(EXIT_FAILURE);
}
if(nb_ligne>1000)
printf("La fonction doit etre appele avec un nombre entre 1 et 1000\n");
else
{
while(m<nb_ligne)
{
int ecrit ;
sprintf(buff,"%d\n",m);
ecrit = write(T, buff, 4*sizeof(char));
if (ecrit == -1)
{
perror("write");
}
m++;
}
}
close(T);
}
void operation_fichier(char* nom, int num,int nb_op)
{
char cmd;
int T;
char buff[4] ;
int i=0;
int j=0;
if(T=open (nom,O_RDWR ) == -1)
{
printf("Erreur\n");
exit(EXIT_FAILURE);
}
while(i<nb_op)
{
printf("Tapez r pour lire une ligne ou w pour ecrire : \n");
scanf("%c",&cmd);
if(cmd=='r')
{
lseek(T,(num-1)*4,SEEK_SET);
read(T,buff,4);
for(j=0;j<4;j++)
{
printf ("%c",buff[j]);
}
}
if(cmd=='w')
{
char saisie;
lseek(T,(num-1)*4,SEEK_SET);
printf("Tapez 3 caracteres :\n");
scanf("%3c",&saisie);
sprintf(buff,"%3c\n",saisie);
write(T,buff,4*sizeof(char));
}
else
{
printf("Erreur, entrez soit r soit w :\n");
operation_fichier(nom,num, nb_op);
}
}
close(T);
}
int main(int argc, char** argv)
{
creer_fichier(100);
operation_fichier("Fichier_test", 10,3);
return EXIT_SUCCESS;
} |
Partager