c -如何在文件的行中添加某些前缀



我有一个名为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 %sn",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);
}

相关内容

  • 没有找到相关文章

最新更新