如何将某些前缀添加到文件中的行

How to add certain prefixes to lines from a file

所以我有一个文本文件(名为 So.txt),其中包含:

Will
Happy
12.50
2012
Kanye
Wolves
15.99
2016

我正在编写一个程序,从中读取并为每个读取行添加一个特定的前缀。基本上我希望输出看起来像这样:

Name of singer: Will
Name of song: Happy
Price: 12.50
Year of release:2012
Name of singer: Kanye
Name of song: Wolves
Price: 15.99
Year of release:2016

这是程序。

song_file = fopen("So.txt", "r");
char singleline[150];
while (!feof(song_file) ) {
                fgets(singleline, 150, song_file);
                puts(singleline);
                printf("Name of singer: ");
                printf("Name of song:           ");
                printf("Price:                  ");
                printf("Year of release:        "); 
                
            } 

我认为你的目标输出如下代码。

或许你可以看看,我们稍后再讨论。

#include <stdio.h>
#include <string.h>
#define STRLEN 10

char Prefix_word[][20]={
    "Name of singer :",
    "Name of song : ",
    "Price : ",
    "Year of release : "
};

void main(void){
    FILE *fd;
    fpos_t Current_pos;
    fpos_t Start_pos;

    char singleline[STRLEN];
    int index=0;
    int len=0;

    fd = fopen("test.txt", "r");
    /* Get the Start position */
    fgetpos(fd, &Start_pos);

    /* Initial string array */
    memset(singleline, ' ', STRLEN);

    while(!feof(fd)){
        /* Counting the lenght of string */
        len++;

        /* Read 1 character to check whether to go to the next column*/
        fread(singleline, sizeof(char), 1, fd);

        if(singleline[0]=='\n'){
            fgetpos(fd, &Current_pos);
            fsetpos(fd, &Start_pos);
            fread(singleline, sizeof(char), len, fd);

            /* Print */
            printf("%s %s\n",Prefix_word[index++], singleline); 

            /* Get Start position */
            fgetpos(fd, &Start_pos);

            /* Initial */
            len=0;
            memset(singleline, ' ', STRLEN);

            if(index>=4){
                printf("================\n");
                index=0;
            }
        }
    }

    fclose(fd);
}