Search code examples
ctextstructfopenrecord

C program to add numbering in txt file


I have a text file name myData.txt it contains the following text:

Bob Smith 5555556666
Wei Song 5555554444
George Snufolopolous 5555556666
William Kidd 5555554444
Hopalong Cassidy 5555556666
Lone Ranger 5555554444
Tonto Ng 5555556666
Pancho Vilas 5555554444
Cisco Kid 5555559999

I want the text of the file myData.txt to change into the following:

1 Bob Smith 5555556666
2 Wei Song 5555554444
3 George Snufolopolous 5555556666
4 William Kidd 5555554444
5 Hopalong Cassidy 5555556666
6 Lone Ranger 5555554444
7 Tonto Ng 5555556666
8 Pancho Vilas 5555554444

The code I am using is in C language and it is:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define MAXSIZE 8
struct Record
{

    int id;

    char firstName[31];

    char lastName[31];

    char cellPhone[11];
};

int main(void)
{
    struct Record record[MAXSIZE];
    int numberOfRecords = 0;
    FILE *fp = NULL;
    int i = 0;
    fp = fopen("myData.txt", "w");
    if (fp == NULL)
    {

        while (fscanf(fp, "%s %s %s", record[i].firstName,

                      record[i].lastName, record[i].cellPhone)

                   != EOF &&
               i < MAXSIZE)

        {

            record[i].id = i + 1;

            numberOfRecords++;

            i++;
        }
    }

    fp = fopen("myData.txt", "a");

    if (fp == NULL)

    {

        for (i = 0; i < numberOfRecords; i++)

        {

            fprintf(fp, "%d%s%s%s\n", record[i].id, record[i].firstName,

                    record[i].lastName, record[i].cellPhone);
        }
    }

    return 0;
}

When I compile this code, the file myData.txt gets empty. What's wrong with this code, kindly comment the link to the resources that might be able to solve the problem.


Solution

  • First things first: You should always close a file before opening it again. Opening a file twice without closing it may corrupt the file and you'll lose the data.

    Second you can do this:

    1. use argc and argv to take myData.txt as command-line input
    2. open myData.txt and one another file and
    3. using fread() read each object in a struct Record's object and 
       write it to another file using fprintf(fp, "%i %s %s %s", i + 1, ... );
    4. repeat 3 until total number of objects are read or EOF is reached.
    5. CLOSE both files and return
    

    Here struct Record would be like:

    struct Record
    {
        char firstName[31];
    
        char lastName[31];
    
        char cellPhone[11];
    };