Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    31
    Rep Power
    2

    Database implementation with files


    Hello !
    I got two problems.
    First one, I'm trying to implemente a database-style program which ask the user to enter informations about his clients and then registers those information in a file for each client. I want to make it dynamic so I do not free what I malloc'd before, otherwise the files would disappear of course.

    But I stumble upon one error : it says I make one static declaration of addclient, followed by a non-static declaration (which is false to me since I put the declaration of the function inside the same block !).

    The code : PASTEBIN*com/9Em59XJ1

    Second problem :
    I try to make a basic filewriting program, which ask the name of the file to write and what to write inside. It compiles but it crashes.
    the program takes the name of the file in argument then should register what the user type until you type "\n" (enter), then put it in the file !
    But I don't want to see what I type in the terminal, I want to use stdin stream.

    The code: PASTEBIN*com/Gid7YJdr

    Thanks for your help ! :)
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    159
    Rep Power
    19
    Please post your code, inside code tags within your post.

    Jim
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    31
    Rep Power
    2
    Alright !
    Database implementation :


    Code:
        #include <stdio.h>
        #include <stdlib.h>
         
        int main()
        {
                int nbr = 0;
            FILE * write;
            struct client
                {
                        char * nom;
                        int gsm;
                        int age;
                };
                typedef struct client Client;
                printf("\nCombien de clients souhaitez vous ajouter dans votre BDD ?\n"); //how much clients in your database?
                scanf("%d", &nbr);
                Client * database = NULL;
                database = malloc(nbr*sizeof(Client));
               
                void addclient( struct client * cli );
               
                int n = 0;
                for(int i = 0; i < nbr; i++)
                {
                        addclient(&database[i]);
                }
               
                for(int k = 0; k < nbr; k++)
                {
                        write = fopen(database[k].nom, "w");
                        fprintf(write, "Nom : %s \nAge : %d \n GSM : %d \n",database[k].nom, database[k].age, database[k].gsm);
                        fclose(write);
                }
               
                void addclient( struct client * cli )
                {
                        printf("\nNom du client :");
                        scanf("%s", cli->nom);
                        printf("\n Age du client : ");
                        scanf("%d", cli->age);
                        printf("\n GSM du client : ");
                        scanf("%d", cli->gsm);
                }
               
                printf("Quel client souhaitez vous consulter ?"); // which client's info do you want to see ?
                scanf("%d", &n);
                FILE * read;
                read = fopen(database[n-1].nom, "r");
                char * filecontent;
                fscanf(read, "%s", filecontent);
                printf("%s", filecontent);
               
        }
    File writer :

    Code:
    	
    
        #include <stdio.h>
         
        #define ACTUEL 0
         
        char * utilisateurs[2] = { "Wally", "Francky" };
         
        main(char sortie[20]) // file writer
        {
                char entree = 'a';
                char c;
                FILE * write;
                write = fopen(sortie, "w");
                while(entree != '\n')
                {
                        entree = fgetc(stdin);
                        fwrite(&entree, sizeof(char), 1, write);
                }
                fclose(write);
               
                FILE * read;
                read = fopen(sortie, "r");
               
                printf("Texte de l'utilisateur %s : ", utilisateurs[ACTUEL]);
                while( !feof(read))
                {
                        fread(&c, sizeof(char), 1, read);
                        printf("%c", c);
                }
                fclose(read);
        }
  6. #4
  7. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,174
    Rep Power
    2222
    Post your actual code, please! The code that you compile and run.

    C does not allow you to place functions inside of other functions. C also does not allow you to declare variables in the middle of the code, even though C99 does allow that. If you are using C99, then you need to inform us of that fact.
  8. #5
  9. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,392
    Rep Power
    1871
    > But I stumble upon one error : it says I make one static declaration of addclient, followed by a non-static declaration
    > (which is false to me since I put the declaration of the function inside the same block !).
    Actually, that makes it true.
    Aside from the fact that C doesn't allow nested functions (though gcc does for some weird reason), defining a nested function HAS to be static, because it no longer has file scope (there's no chance you could call addclient from another module, as written).

    Assuming you compile in C99 mode (for the for loop declaration issue), the next big thing to fix are the printf format mis-matches.
    Code:
    $ gcc -Wall foo.c
    foo.c: In function ‘main’:
    foo.c:23:3: error: ‘for’ loop initial declarations are only allowed in C99 mode
    foo.c:23:3: note: use option -std=c99 or -std=gnu99 to compile your code
    foo.c:28:3: error: ‘for’ loop initial declarations are only allowed in C99 mode
    foo.c:35:8: error: static declaration of ‘addclient’ follows non-static declaration
    foo.c:20:8: note: previous declaration of ‘addclient’ was here
    foo.c: In function ‘addclient’:
    foo.c:40:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat]
    foo.c:42:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat]
    foo.c: In function ‘main’:
    foo.c:53:1: warning: control reaches end of non-void function [-Wreturn-type]

    > Program 2
    Code:
        main(char sortie[20]) // file writer
        {
                char entree = 'a';
                char c;
                FILE * write;
                write = fopen(sortie, "w");
    Read your book again to rediscover argc and argv.
    Simply saying char sortie[20] doesn't magic the parameter (argc) into a string.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    31
    Rep Power
    2
    @dwise : the code that I sent compiles and runs in C99.

    Yes I use C99, sorry for not telling it but you must have seen it since I use "for" loops with declaration inside them.
    You must use weird IDE with bizarre versions of compilers which are not up to date. I use MingW and compile with GCC in console.

    Now for the main problems:

    I put addclient in static and if I put it outside of the main block it says I use incomplete pointers ?
    One of my problems I think is to understand when to use -> operators, only to access structures' variables in a function where I pass a pointer to a structure in the argument of this function? like in the printf of my addclient block, should I use &cli.nom or cli-> nom ?

    Also how should I put functions so I can access them in my main block ? Do I have to put static in front of them when they are nested or should I put them outside the main block ?

    Also I understood for the addclient parameter and put & inside its argument of course, because it required a pointer.
    So my last error is to understand the scope of the function and the -> operator.

    For the filewriter program, I remplaced the char sortie[20] by char * sortie but it still crashes ! Sadly in my book they don't explain how I can prevent errors while making, writing and opening files (I come from the Java language where you can use throw/catch to prevent from errors but in my book they don't tell me how to use those).

    Thanks for your help so far !

    EDIT: I put static in front of prototype and in front of the function which is nested inside the main block and only error I get is "invalid store class for addclient" which I do not understand. Also I kinda upgraded my code and put the fopen, fwrite and fclose operations inside the addclient function, and removed the second for loop you can see above (the one with the k). :)
  12. #7
  13. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,392
    Rep Power
    1871
    Here is your first program, with a better structure.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    struct client {
      char *nom;
      int gsm;
      int age;
    };
    typedef struct client Client;
    void addclient(struct client *cli);
    
    int main()
    {
      int nbr = 0;
      FILE *write;
      printf("\nCombien de clients souhaitez vous ajouter dans votre BDD ?\n"); //how much clients in your database?
      scanf("%d", &nbr);
      Client *database = NULL;
      database = malloc(nbr * sizeof(Client));
    
      int n = 0;
      for (int i = 0; i < nbr; i++) {
        addclient(&database[i]);
      }
    
      for (int k = 0; k < nbr; k++) {
        write = fopen(database[k].nom, "w");
        fprintf(write, "Nom : %s \nAge : %d \n GSM : %d \n", database[k].nom, database[k].age,
                database[k].gsm);
        fclose(write);
      }
    
      printf("Quel client souhaitez vous consulter ?"); // which client's info do you want to see ?
      scanf("%d", &n);
      FILE *read;
      read = fopen(database[n - 1].nom, "r");
      char *filecontent;
      fscanf(read, "%s", filecontent);
      printf("%s", filecontent);
    
    }
    
    void addclient(struct client *cli)
    {
      printf("\nNom du client :");
      scanf("%s", cli->nom);
      printf("\n Age du client : ");
      scanf("%d", cli->age);
      printf("\n GSM du client : ");
      scanf("%d", cli->gsm);
    }
    Now, to fix these errors
    Code:
    $ gcc -W -Wall -std=c99 foo.c
    foo.c: In function ‘addclient’:
    foo.c:47:3: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat]
    foo.c:49:3: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat]
    foo.c: In function ‘main’:
    foo.c:37:9: warning: ‘filecontent’ is used uninitialized in this function [-Wuninitialized]

    > For the filewriter program, I remplaced the char sortie[20] by char * sortie but it still crashes !
    Oh please - just read your book and discover that it should be
    int main ( int argc, char *argv[] )
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    31
    Rep Power
    2
    how is it a better structure ? you just put the structure definition and the prototype of addclient before the main block, which is not necessary from what I've read.
    int main ( int argc, char *argv[] ) => this is not necessary and its not written in my book, I made other programs that work with char * string.
    Also an array of char "magic" it into a string , the following code works in another program I made :
    Code:
    FILE * read;
    char nom[20];
    read = fopen(nom, "r");
    
    // or if you still don't understand, this works:
    
    char nom[20];
    gets(nom);
    printf("%s", nom);
    
    // and it also works with pointer on arrays :
    
    char * phrase;
    gets(phrase);
    printf("%s", phrase);
    And I don't get your printf errors !
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    31
    Rep Power
    2
    So I just understood now you meant the scanf one.
    heres a code that compiles and runs (no need for c99) but it crashes

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    FILE * write;
    
    struct client
    {
    	char * nom;
    	int gsm;
    	int age;
    };
    
    struct client * database = NULL;
    
    void addclient( struct client * cli );
    
    int main()
    {
    	int nbr = 0;
    	int n = 0;
    	int i;
    
    	typedef struct client Client;
    	printf("\nCombien de clients souhaitez vous ajouter dans votre BDD ?\n"); //how much clients in your database?
    	scanf("%d", &nbr);
    	database = malloc(nbr*sizeof(Client));
    	
    	for(i = 0; i < nbr; i++)
    	{
    		addclient(&database[i]);
    	}
    	
    	
    	printf("Quel client souhaitez vous consulter ?"); // which client's info do you want to see ?
    	scanf("%d", &n);
    	FILE * read;
    	read = fopen(database[n-1].nom, "r");
    	char * filecontent;
    	fscanf(read, "%s", filecontent);
    	printf("%s", filecontent);
    	
    }
    
    void addclient( struct client * cli )
    {
    	printf("\nNom du client : ");
    	scanf("%s", &cli->nom);
    	printf("\nAge du client : ");
    	scanf("%d", &cli->age);
    	printf("\nGSM du client : ");
    	scanf("%d", &cli->gsm);
    	write = fopen(cli->nom, "w");
    	fprintf(write, "Nom : %s \nAge : %d \n GSM : %d \n",&cli->nom, &cli->age, &cli->gsm);
    	fclose(write);
    }
    Also the code of filewriter program which also compiles and runs and do not crash but display crap after I ask him to display the content of the file I just wrote :

    Code:
    #include <stdio.h>
    
    #define ACTUEL 0
    
    char * utilisateurs[2] = { "Wally", "Francky" }; 
    
    main(int argc, char * argv[]) // file writer
    {
        char entree = 'a';
    	char c;
    	FILE * write;
    	write = fopen(argv[0], "w");
    	while(entree != '\n')
    	{
    		entree = fgetc(stdin);
    		fwrite(&entree, sizeof(char), 1, write);
    	}
    	fclose(write);
    	
    	FILE * read;
    	read = fopen(argv[0], "r");
    	
    	printf("Texte de l'utilisateur %s : ", utilisateurs[ACTUEL]);
    	while( !feof(read))
    	{
    		fread(&c, sizeof(char), 1, read);
    		printf("%c", c);
    	}
    	fclose(read);
    }
  18. #10
  19. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,174
    Rep Power
    2222
    The only IDEs I use are Visual Studio, which does not support C99 and undoubtedly never will, and specialized IDEs for embedded programming. Otherwise, I use MinGW gcc and compile from the command line.

    When you use gcc, you need to tell it to show you warnings.

    Here is what I get when I compiled your first program:
    C:TEST>gcc -Wall hooby1.c
    hooby1.c: In function `main':
    hooby1.c:36: parse error before `*'
    hooby1.c:37: `read' undeclared (first use in this function)
    hooby1.c:37: (Each undeclared identifier is reported only once
    hooby1.c:37: for each function it appears in.)
    hooby1.c:38: parse error before `char'
    hooby1.c:39: `filecontent' undeclared (first use in this function)
    hooby1.c:42: warning: control reaches end of non-void function
    hooby1.c: In function `addclient':
    hooby1.c:47: warning: char format, pointer arg (arg 2)
    hooby1.c:53: warning: char format, pointer arg (arg 3)
    hooby1.c:53: warning: int format, pointer arg (arg 4)
    hooby1.c:53: warning: int format, pointer arg (arg 5)

    C:TEST>
    You said that you had removed the need for C99 support, but you were wrong. After correcting for the declarations in midst of code, I get:
    C:TEST>gcc -Wall hooby1.c
    hooby1.c: In function `main':
    hooby1.c:42: warning: control reaches end of non-void function
    hooby1.c: In function `addclient':
    hooby1.c:47: warning: char format, pointer arg (arg 2)
    hooby1.c:53: warning: char format, pointer arg (arg 3)
    hooby1.c:53: warning: int format, pointer arg (arg 4)
    hooby1.c:53: warning: int format, pointer arg (arg 5)

    C:TEST>
    You forgot to return from main.
    In the scanf on line 47, cli->nom is already a pointer so it doesn't need the address operator.
    In the fprintf on line 53, you are using the address operator to convert all those fields to their addresses and yet you are telling fprintf to print out a string and integers, which I would assume to be the values in cli.

    Also, where do you malloc any memory for cli->nom to point to? Once you fixed that warning, you would still be using an uninitialized pointer, a garbage address, to store the input string. Which would very likely result in a crash due to an access violation.

    As for your second "doesn't need C99" program, after having to yet again correct a misplaced declaration I get:
    C:TEST>gcc -Wall hooby2.c
    hooby2.c:8: warning: return-type defaults to `int'
    hooby2.c: In function `main':
    hooby2.c:31: warning: control reaches end of non-void function

    C:TEST>
    So the only problems it found is that you don't know how to write a main function. So then your problem there must be a logic problem which doesn't present itself to me readily. Have you read the file to verify that it is what you expect? If it isn't, then you have a problem in writing to the file. If it is, then it's the read section that's doing something wrong. Of course, if the write section is wrong that doesn't mean the read section is right, so you would need to fix the write section first and then see whether the read section works.

    Always remember to use -Wall to display all warnings.
  20. #11
  21. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    31
    Rep Power
    2
    Okay thanks a lot for your reply, never knew there were warnings and that I could display them, I'm only started in C (through I finished the book I read and try to make a functioning program that use all the different concepts explained (files, structures, pointers, strings, ...)).

    So it compiles with C99, even with the warnings for me (but that's not a good programming habit to compile with warnings I know).

    The main problem I encounter is that we can't put numbers in a string ?? That's really a shame and makes things way more complicated (In java it's much simpler...), I wonder how I can read my file then...

    For the filewriter, it makes a file but the number age and gsm are different, but it only works if I only put one letter in the name of the file/client otherwise it crashes, must be because the address point to the first char which is very strange, I made another program which works (ask the user one string with gets then open and write the string inside the file).

    I did not understand what you said about malloc(), could you explain more ? (its first time I try to use malloc, I understood it was used to dynamically allocate arrays, and I don't use free() because otherwise it would destroy the files).

    Again, thanks you very much for your help and fast answers :)
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    31
    Rep Power
    2
    In fact I realized I made exactly the same program that I made before I'm so dumb... except that I want the program to be able to use the name of the file as an argument. If I don't put it in argument it works ( meaning if I put the name of the file as a constant or ask the user to enter it then open the file with that user string...)
    So please tell me how I can use char * argv[], its not written in my book.. I just do write = fopen(argv[0], "w"); but it doesnt write it... :(

    Thanks a lot again, that would solve the problem of the filewriter.
    For the database one, I think I would have to rewrite it completely because I couldn't read it with just doing fscanf("%s", filecontent); then do printf("%s", filecontent); if there are INTEGERS in it, from what I understood...

    Maybe somebody got a solution for the database one ? :)

    Thanks a lot again
  24. #13
  25. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,174
    Rep Power
    2222
    We should not consider our programs to compile cleanly unless they compile without warnings. Warnings tell us that something might not be right with our program. More often than not, warnings tell us where we made a mistake. Warnings are much more important than error messages are. We should never ignore warnings.

    Yes, you can put a number in a string. Use sprintf. It's just like printf and fprintf except it outputs to a string.

    Pointers are an integral part of C. You cannot write much C without having to use pointers. Java does not have pointers but rather uses references instead, so I would think that pointers are a new concept for you.

    Every data item and function resides in the computer's memory and each one has its own location in memory. Each memory location has a unique memory address. Pointers contain memory addresses, such that if a pointer points to an integer value, that means that that value is stored in a memory location and the pointer contains the address of that location.

    In a way, we can think of pointers as a tactical soldier or police officer thinks about his firearm when in a tactical situation where: he has to always be aware of where he is pointing that firearm, which is called "muzzle discipline". When we work with pointers, we must always be aware of where those pointers are pointing. Specifically, we must be absolutely certain that a pointer is pointing to a memory location that is safe for us to write to.

    This is further complicated by the fact that pointers always are pointing somewhere, even when we haven't initialized them yet. It is a simple fact of computer hardware that all memory locations contain a value, even if it's a random value from the bits settling to ones or zeros upon power-up depending on which subtle differences in each bit cell's individual electronics. By the time that you have loaded your program into memory and have started executing it, the memory locations it's using have very likely already been used by other programs and those locations are still set to the last values that had been written to them. The highly technical computer-science term for these near-random residual values is garbage. So until you have written a known value to a variable, be it scalar or pointer, it contains a garbage value. You must never use an uninitialized variable because you never know what value it contains and you most definitely must not use an uninitialized pointer, because you have no idea where it's pointing. Just as you would not discharge a firearm without first ensuring that it is pointing exactly where you want it to point. Most of the time, an uninitialized pointer will be pointing to memory that does not belong to you and that the operating system must protect from you, so when you try to access it the operating system will terminate your program and it will crash.

    database is a pointer. You used malloc to assign memory to it so that it could be used like an array. That initialized database and made it safe to use it. That was correct procedure.

    Within struct client is a field, nom, which is a char pointer. When you try to use it with scanf, it has not been initialized, so it contains garbage and so could be pointing anywhere. When you scanf the name in, it gets written to that random location, which would cause something to be overwritten if it just happened to be within your own memory space, in which case you will be plagued by weird and "inexplicable" corrupted data. If instead you are lucky, it will point outside your memory space and you will crash.

    nom has to point to somewhere that is safe to write to. I can think of three possible things that you could to to guarantee that:

    1. You could malloc some memory to it that is enough to hold the longest possible name plus one more character for the null-terminator.

    2. Instead of declaring nom to be a char pointer, declare it to be a char array whose size is large enough to hold the longest possible name plus one more character for the null-terminator.

    or 3. Declare a local char array of sufficient size to serve as an input buffer to use with scanf("%s" . Then when you have input a name, use the function strdup to copy it to nom. strdup calls malloc to allocate enough memory to hold the string plus one for the null-terminator and then copies the string to that memory. Or instead of using strdup you could call malloc and strcpy yourself to do the same thing.

    You do not need to use free until you are ready to get rid of those structs. Or to reuse them, since you would need to free nom before you could assign a new name to it. Same thing if you free database, because you would first need to go to each struct in database and free each nom field before you could free database itself. Failure to do so would create memory leaks, which is a particularly insidious type fo bug.

    When you program in C, you are often working closer to the hardware than with most other languages, so there is a lot more that you have to keep in mind.

    I hope that wasn't too much for you to digest.
  26. #14
  27. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,174
    Rep Power
    2222
    Originally Posted by hooby.graphite
    So please tell me how I can use char * argv[], its not written in my book.. I just do write = fopen(argv[0], "w"); but it doesnt write it... :(
    Sorry, I missed that.

    argv is an array of char pointers, hence an array of strings. argc tells you how many there are.

    argv[1] is the first command-line argument, argv[2] the second, and so on. argv[0] is very special: it is the name of the program. Sometimes it includes the directory path to the program and sometimes it does not; that seems to depend on the operating system and the manner in which the program was invoked.

    So then, if you pass the filename to the program as an argument and it's the first argument, then you will find it in argv[1] and not in argv[0]. argv[0] is the program and you don't want to be writing to that.

    PS

    Here's a test program I wrote seven years ago which I called args.c:
    Code:
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
        int i;
        
        printf("argc = %d\n",argc);
        for (i=0; i<argc; i++)
            printf("argv[%d] = \"%s\"\n",i,argv[i]);
        
        return 0;        
    }
    I just now compiled and ran it with the following arguments (yes, I'm usually too lazy to name my executable):
    C:\otros\pc14402\dcw\PROJECTS\TEST>a 123 234 file -x /? "too many secrets"
    argc = 7
    argv[0] = "a"
    argv[1] = "123"
    argv[2] = "234"
    argv[3] = "file"
    argv[4] = "-x"
    argv[5] = "/?"
    argv[6] = "too many secrets"

    C:TEST>
    And now you know how to use argc and argv[]. Plus you now know how to read option switches (eg, -x, /?) from the command line.

    PPS

    OK, to make it clearer, I gave the executable a name, args.exe:
    C:TEST>gcc -Wall args.c -o args.exe

    C:TEST>args 123 234 file -x /? "too many secrets"
    argc = 7
    argv[0] = "args"
    argv[1] = "123"
    argv[2] = "234"
    argv[3] = "file"
    argv[4] = "-x"
    argv[5] = "/?"
    argv[6] = "too many secrets"

    C:TEST>
    Last edited by dwise1_aol; August 7th, 2013 at 05:28 PM.
  28. #15
  29. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    31
    Rep Power
    2
    Thanks, I had seen an exemple on Internet before seeing your program, and it works with argv[1] now ! This is not explicit :p Thanks a lot for your help so now filewriter is done, only one left is the database implementation...

    Also I noticed that using fprintf or fscanf is really a bad idea (crashes etc)... an advice to somebody who want to scan a file : use fgets and sscanf, nuff said, very important.

    so if anybody got an idea how to resolve database implementation I would be very happy...
    Maybe it comes from the malloc() but I need some explanations, it's covered almost briefly in my book...
    Thanks a lot for your help.

    Last implementation:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    FILE * write;
    char * test;
    
    struct client
    {
    	char * nom;
    	int gsm;
    	int age;
    };
    
    struct client * database = NULL;
    
    void addclient( struct client * cli );
    
    int main()
    {
    	int nbr = 0;
    	int n = 0;
    	int i;
    
    	typedef struct client Client;
    	printf("\nCombien de clients souhaitez vous ajouter dans votre BDD ?\n"); //how much clients in your database?
    	scanf("%d", &nbr);
    	database = malloc(nbr*sizeof(Client));
    	
    	for(i = 0; i < nbr; i++)
    	{
    		addclient(&database[i]);
    	}
    	
    	printf("Quel client souhaitez vous consulter ?"); // which client's info do you want to see ?
    	scanf("%d", &n);
    	FILE * read;
    	read = fopen(database[n-1].nom, "r");
    	char * filecontent;
    	fgets(filecontent, 20, write);
    	printf("%s", filecontent);
    	
    	return 0;
    	
    }
    
    void addclient( struct client * cli )
    {
    	printf("\nNom du client : ");
    	scanf("%s", cli->nom);
    	write = fopen(cli->nom, "w");
    	printf("\nAge du client : ");
    	scanf("%d", cli->age);
    	printf("\nGSM du client : ");
    	scanf("%d", cli->gsm);
    	fprintf(write, "Nom : %s \nAge : %d \n GSM : %d \n",cli->nom, cli->age, cli->gsm);
    	fclose(write);
    }
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo