0

commands.txt というテキスト ファイルがあり、いくつかのコマンドの後にいくつかの引数が続きます。例:

STOP 1 2 4
START 5 2 1 8
MOVE
CUT 0 9

このテキストファイルからすべての行を読み取り、このようなものを印刷したい

STOP: 1 2 3
START: 5 2 1 8
MOVE:
CUT: 0 9

fgets を使用してすべての行を読み取り、sscanf を使用してみましたが、機能しません。

char line[100]   // here I put the line
char command[20] // here I put the command
args[10]         // here I put the arguments



 #include<stdio.h>
    int main()
    {
    FILE *f;
char line[100];
char command[20];
int args[10];

f=fopen("commands.txt" ,"rt");
while(!feof(f))
{
fgets(line , 40 , f);
//here i need help
}
fclose(f);
return 0;
}

手伝って頂けますか?

4

1 に答える 1

0

あなたはすべてを間違った方向に進めていると思います。コマンドを引数とは別に収集して何かを実行したい場合は、ctype.h を使用してテストする必要があります。

ただし、出力を行う方法については、これらすべてのバッファーを実際に保存する必要はありません。全体を印刷して、必要な場所にコロンを記入してください。

    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>

    int main(){

      FILE *f;
      char *buf;
      buf = NULL;
      int i = 0, size;

      f=fopen("commands.txt", "r");
      fseek(f, 0, SEEK_END);
      size = ftell(f);
      fseek(f, 0, SEEK_SET);
      buf = malloc(size + 1);
      fread(buf, 1, size, f);
      fclose(f);

      for(i = 0; i < size ; i++){
        while(isalpha(buf[i])){
          printf("%c", buf[i++]);
        }
        printf(":");
        while(buf[i] == ' ' || isdigit(buf[i])){
          printf("%c", buf[i++]);
        }
        printf("\n");
      }
    return 0;
    }
于 2013-06-13T22:20:35.473 に答える