0
#include <stdio.h>

int main()
{
   FILE *fp;
   char str[60];
   char data[50];
   char * pch;

   /* opening file for reading */
   fp = fopen("DATAtest.txt" , "r");
   if(fp == NULL) {
      perror("Error opening file");
      return(-1);
   }
   if( fgets (str, 60, fp)!=NULL ) {
      /* writing content to stdout */
      //puts(str);
   }
if( fgets (str, 60, fp)!=NULL ) {
      /* writing content to stdout */
      puts(str);

printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
    {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
      }
       fclose(fp);
       return(0);
    }

基本的には、ファイルを開いて 2 行目からデータを抽出します。次に行う必要があるのは (次の行から: printf ("Splitting...))、取得したテキストを個別の文字に分割することです。たとえば、次のテキストを取得します " 0 0 128 0 0 0 0 0 0 0; 私はそれを次のように分割したいと思います:

0 
0
128
0
0
0
0
0
0
0

これで始めたばかりのコードで申し訳ありません。

4

3 に答える 3

1
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>

 int main(){
     FILE *fp;
     char str[60] = " 0 0 128 0 0 0 0 0 0 0;";//from fgets
     char *data[50];//or char data[max number of parts][max of lengh of parts]
     char *pch;
     const char *delimiter = " ,.-;";
     int i, cnt = 0;

     printf ("Splitting string \"%s\" into tokens:\n",str);

     pch = strtok (str, delimiter);
     while (pch != NULL){
         //printf ("%s\n", pch);
         //strcpy(data[cnt++], pch);//by 2D array, Not necessary free.
         data[cnt++] = strdup(pch);//make clone. it's not standard function.
         pch = strtok (NULL, delimiter);
     }
     for(i = 0; i<cnt; ++i){
         printf("%s\n", data[i]);
         free(data[i]);//release
     }
     return(0);
 }
于 2014-09-01T11:53:38.407 に答える
0

DATAtest.txt私はこれがあなたのファイルがどのように見えるかを仮定します:

abcd pqr strm
" 0 0 128 0 0 0 0 0 0 0;
xyz abr

私はあなたのコードに小さな変更を加えました:

#include <stdio.h>
#include <string.h>

int main()
{
   FILE *fp;
   char str[60];
   char data[50];
   char * pch;

   /* opening file for reading */
   fp = fopen("DATAtest.txt" , "r");
   if(fp == NULL) {
      perror("Error opening file");
      return(-1);
   }
   if( fgets (str, 60, fp)!=NULL ) {
      /* writing content to stdout */
      //puts(str);
   }
   if( fgets (str, 60, fp)!=NULL ) 
   {
        /* writing content to stdout */
        puts(str);
        str[strlen(str)-1]='\0'; // Remove \n from str
        printf ("Splitting string \"%s\" into tokens:\n",str);
        pch = strtok (str,"\" ,.-;"); //Mention required delimiters 
        while (pch != NULL)
        {
            printf ("%s\n",pch);
            pch = strtok (NULL, "\" ,.-;");//Mention required delimiters
        }
    }
    fclose(fp);
    return(0);
}

出力

" 0 0 128 0 0 0 0 0 0 0;

Splitting string "" 0 0 128 0 0 0 0 0 0 0;" into tokens:
0
0
128
0
0
0
0
0
0
0
于 2014-08-31T16:58:16.210 に答える