如何解析每行包含一长串数字的文件?

时间:2013-07-23 07:04:02

标签: c file-io

我的文件如下:

1 2 300 500 5 117 5 90 45 34 ---- -------------- 34566

7 8 16 8 39 167 80 90 38 4555

等等 我如何得到每个数字并存储一个二维数组?

到目前为止,我可以使用fgets()函数读取该行。

FILE *fp = NULL;
char buffer[1024];
 fp = fopen("Input.txt","r"); 
if(fp!=NULL)
{
  while(fgets(buffer,1024,fp)!=NULL)
  {
    // i need help here

   } 
 }

是否有另一种解决方法(比这更好)而不是使用fgets()?

3 个答案:

答案 0 :(得分:1)

可能是这样的:

int i = 0;
int num[20];
while (buffer[i] != '\0')
{
  int j = 0;
  char a[80];
  while (buffer[i] != ' ')
  {
    a[j] = buffer[i];
    ++j;
    ++i;
  }
  if (buffer[i] == '\0')
    break;
  a[j] = '\0';
  const char* b = &a[0];
  num[i] = strtol(b, NULL, 10);
  ++i;
}

......虽然这里的内存管理很脏。要做好工作。

答案 1 :(得分:1)

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

int main(void){
    //Either the two-pass or ensure dynamically allocate and expand by `realloc` if size of the array can't be determined in advance, 

    static int array[20][20];
    int row=0;
    FILE *fp = NULL;
    char buffer[1024];
    fp = fopen("Input.txt","r"); 
    if(fp!=NULL) {
        while(fgets(buffer,1024,fp)!=NULL){
            char *p = buffer, *endp;
            long num;
            int col = 0;
            do{
                num = strtol(p, &endp, 10);
                if(*endp == ' ' || *endp == '\n' || *endp == '\0'){
                    array[row][col++] = num;
                }
                p = endp + 1;
            }while(*endp != '\n' && *endp != '\0');
            ++row;
        }
        fclose(fp);
    }
    return 0;
}

答案 2 :(得分:0)

工作代码:

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

int main()
{
    char *str_avail;
    char *token;
    FILE *fp = NULL;
    char buffer[1024];
    char buffer2[1024];

    fp = fopen("test.txt","r"); 
    if(fp!=NULL)
    {
        while(fgets(buffer,1024,fp)!=NULL)
        {
            printf("%s\n", buffer);
            str_avail = strpbrk(buffer, ":");
            if(*buffer == '\n')
                continue;
            strcpy(buffer2, str_avail+2);
            token = strtok(buffer2, " ");
            while(token != NULL){
                    printf("%s\n", token);
                        token = strtok (NULL, " ");
            }
        } 
    }
}