Writing from struct into a txt file

I have some code that reads in the user input into a struct, how ever i want to print this input into a text file but i have no idea how to do that. I have the code for the user input but i think i need to put this into a loop so it reads the input into the .txt file. Can any one help?

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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main()
{
    //declaring the struct
    struct customer
    {
        int ID;
        int age;
        char gender;
        char name [40];
        char surname [40];
        char address [100];
    };//end to customer sturucture
    
    
    FILE *fpcust;   //declaring a file variable pointer for customers txt file 
    struct customer new_customer;
    
    
    char ch;
    int ID [20];
    int i;
    
    fp = fopen ("c:\\customers.txt", "w");   //opening file for writing 
    
    if (fp == NULL) //error check
    {
        printf("Cannot open file. \n");
    }
    
    //structure for reading the new customer
    
    printf("Please enter your ID. \n");
    scanf("%d", &new_customer.ID);
    
    printf("Please enter your age. \n");
    scanf("%d%*c", &new_customer.age);
    
    printf("Please enter your gender. ( m or f ) \n");
    scanf("%c%*c", &new_customer.gender);
    
    printf("Please enter your firstname. \n");
    gets(new_customer.name);
    
    printf("Please enter your surname. \n");
    gets(new_customer.surname);
    
    printf("Please enter your address. \n");
    gets(new_customer.address);
    
    
    fclose(fp); //closing the file   
    
}
  
You can use function fprintf

For example

1
2
3
4
5
6
fprintf( fp, "%d %d %c %s %s %s\n", new_customer.ID, 
                                    new_customer.age,
                                    new_customer.gender,
                                    new_customer.name,
                                    new_customer.surname,
                                    new_customer.address ); 
Last edited on
ok i see,and will that print the input at the end of file?
It will print record by record.
does it need to be in a loop or just put it in under neither where the struct input is?
of course only after entering a record you can print it in the file.
haha silly question i know sorry, thanks for all the help man!
Topic archived. No new replies allowed.