代码读取由冒号分隔的文本文件:格式如下
1111:2222:3333
如何将冒号分隔的值存储到单独的变量中?
任何帮助将不胜感激。
程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int read_file();
int main()
{
read_file(); // calls function to read file
return 0;
}
// read text file function
int read_file()
{
char line[100];
char file_location[40];
FILE *p_file;
printf("Enter file location: ");
scanf("%s",file_location);
p_file =fopen(file_location, "r");
if(!p_file)
{
printf("\n File missing:");
return 0;
}
while(fgets(line,100,p_file)!=NULL)
{
printf("%s \n",line);
}
fclose(p_file);
return 0;
}
答案 0 :(得分:2)
这会给你一个提示:
像阅读csv文件一样使用strtok
while(fgets(line,100,p_file) != NULL)
{
char *p = strtok(line, ":");
while(p)
{
printf("%s\n", p); //Store into array or variables
p=strtok(NULL, ":");
}
}
答案 1 :(得分:1)
战俘已经给了你需要知道的一切。 那么,FWIW: C编码器所做的一件事就是保留一个简单的utitlies库。使用分隔符敲击字符串是其中一个实用程序。
这是一个非常简单的(无错误检查)示例:
char **split(char **r, char *w, const char *src, char *delim)
{
int i=0;
char *p=NULL;
w=strdup(src); // use w as the sacrificial string
for(p=strtok(w, delim); p; p=strtok(NULL, delim) )
{
r[i++]=p;
r[i]=NULL;
}
return r;
}
int main()
{
char test[164]={0x0};
char *w=NULL; // keep test whole; strtok() destroys its argument string
char *r[10]={NULL};
int i=0;
strcpy(test,"1:2:3:4:hi there:5");
split(r, w, test, ":\n"); // no \n wanted in last array element
while(r[i]) printf("value='%s'\n", r[i++]);
printf("w='%s' test is ok='%s'\n",
(w==NULL)? "NULL" : w, test);// test is still usable
free(w); // w is no longer needed
return 0;
}