私はCプログラミング言語に不慣れです。テキストファイルから特定の文字列を検索して配列にし、それらの配列から単一の文字列を生成するにはどうすればよいですか?
テキストファイル:
name1,name2,name3,type1,g1,g2,g3
name1,last1,last2,type2,g4,g6,g7
foo1,foo2,foo3,type3,gx,g3,g5
foo1,doo1,doo2,type4,g1,gt,gl
出力は1つの文字列である必要があり、分離されていない必要があります。
printf("%s", strings);
次のような出力が得られます。
2 records found
Name: name1,name2,name3
type: type1
g1 type: g1
g2 type: g2
g3 type: g3
Name: name1,last1,last2
type: type2
g1 type: g4
g2 type: g6
g3 type: g7
これまでの私の試みは、テキストファイルを取得して文字列を検索することです。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
char tmp[1000];
int count=0;
FILE *fp=fopen("test.csv","r");
while(fgets(tmp, sizeof(tmp),fp) != NULL){
if (strstr(tmp, "name1")){
count = count + 1;
printf("%s", tmp);
}
}
}
これは出力のみを提供します:
name1,name2,name3,type1,g1,g2,g3
name1,last1,last2,type2,g4,g6,g7
進行中の試み:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
char tmp[1000];
int count=0;
char *string;
char *name1, *name2, *name3, *type,*g1,*g2,*g3;
FILE *fp=fopen("test.csv","r");
while(fgets(tmp, sizeof(tmp),fp) != NULL){
name1 = strtok(tmp,",");
name2 = strtok(NULL,",");
name3 = strtok(NULL,",");
type= strtok(NULL,",");
g1= strtok(NULL,",");
g2= strtok(NULL,",");
g3= strtok(NULL,",");
if (strstr(tmp, "name1")){
count = count + 1;
string = malloc(sizeof(*string));
sprintf(string, "\n%d record(s) found.\n\nName: %s, %s, %s \nType: %s\ng1 type: %s\ng2 type: %s\ng3 type: %s", count, name1, name2,name3,type,g1,g2,g3);
}
}
printf("%s", string);
}
出力付き:
2 record(s) found.
Name: name1, last1, last2
Type: type2
g1 type: g4
g2 type: g6
g3 type: g7