[英]C strings from text file
我是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
首先,您需要使用strtok
分隔行。 在此處閱讀文檔。
獲得所需的所有字段后,使用snprintf
它們輸出到一個字符串中
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 1000
int main(){
char tmp[BUFFER_SIZE];
int count=0;
char string[BUFFER_SIZE];
char all_records[BUFFER_SIZE];
char *name1, *name2, *name3, *type,*g1,*g2,*g3;
FILE *fp=fopen("test.csv","r");
while(fgets(tmp, BUFFER_SIZE,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++;
// snprintf is very similar to printf, see the reference [here][2]
snprintf(string, BUFFER_SIZE,"\nName: %s, %s, %s \nType: %s\ng1 type: %s\ng2 type: %s\ng3 type: %s", name1, name2,name3,type,g1,g2,g3);
strcat(all_records, string); // combine new correct record
}
}
snprintf(string, BUFFER_SIZE, "%d record(s) found.\n", count);
strcat(string, all_records); // add the number of records to the start
// You can use the return value of snprintf to evaluate the size of all things you will print.
printf("%s", string);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.