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 回答