简体   繁体   English

C读取冒号分隔的文本文件

[英]C read colon delimited text file

The code reads a text file delimited by colons : and formatted as follows 该代码读取以冒号分隔的文本文件,其格式如下

1111:2222:3333 1111:2222:3333

How would I store the values separated by colons : into separate variables ? 如何将用冒号分隔的值存储在单独的变量中?

any help would be appreciated. 任何帮助,将不胜感激。

program code: 程序代码:

#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;
}

This will give you a hint : 这会给你一个提示:

Use strtok as you would do for reading a csv file 使用strtok就像读取csv文件一样

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, ":");
    }
}

POW already gave you everything you need to know. POW已经为您提供了您需要了解的一切。 So, FWIW: One of the things C coders do is to keep a library of simple utitlies. 因此,FWIW:C编码人员要做的一件事就是保留简单实用程序的库。 Whacking a string up using delimiters is one of those utilities. 使用定界符重击字符串是这些实用程序之一。

Here is a very simple (no error checking) example: 这是一个非常简单(无错误检查)的示例:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM