C程序在txt文件中添加编号

C program to add numbering in txt file

我有一个文本文件名myData.txt 它包含以下文本:

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

我想将文件 myData.txt 的文本更改为以下内容:

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

我使用的代码是C语言的,是:

#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;
}

当我编译这段代码时,文件 myData.txt 变空了。这段代码有什么问题,请评论link到可能能够解决问题的资源。

首先要做的事:您应该总是在再次打开文件之前先关闭它。打开一个文件两次而不关闭它可能会损坏文件并且您会丢失数据。

其次你可以这样做:

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

这里 struct Record 就像:

struct Record
{
    char firstName[31];

    char lastName[31];

    char cellPhone[11];
};