读取文件,只获取整数并继续运行直到结束

时间:2016-03-21 22:44:35

标签: c file

#include <stdio.h>


int getIntegers(char *filename,int a[]);

int main(void) {
    /////
    FILE *fp;
    char file[10] = "random.txt";
    fp = fopen(file, "w");
    fprintf(fp, "1 2 -34 56 -98 42516547example-34t+56ge-pad12345\n");
    fclose(fp);
    /////

    int i;

    int a[100]; 
    int n = getIntegers(file,a);
    //Here i want to print out what i got from getIntegers. What it should put out = "1 2 -34 56 -98 42516547 -34 56 12345"
    if (n > 0) 
    {
        puts("found numbers:");
        for(i = 0;i < n; i++)
            {
                printf("%d ",a[i]);    
            }
        putchar('\n');
    }
    return 0;
}

int getIntegers(char *filename, int a[])
{
    int c, i;
    FILE *fp;
    fp = fopen(filename, "r");
//I want what this code does to be done with the commented code under it. This will give "1 2 -34 56 -98 42516547"
    while (fscanf(fp,"%d",&i)==1) 
    {
        printf("%d ",i);
    }
    fclose(fp);

// I want this code to give  "1 2 -34 56 -98 42516547 -34 56 12345"  
//    while ((c = fgetc(fp)) != EOF) 
//    {           
//        for(i = 0; i < c;i++)
//        {
//            fscanf(fp, "%1d", &a[i]);
//        }
//    }
//    return i;
}

我有一个包含数字和单词/字母的文件。使用此代码,我得到整数直到第一个字母,但我想继续直到EOF。然后返回这些数字并将它们打印出来。我尝试但无法让它工作。我应该怎么做才能让这个工作?或者我做错了什么。

1 个答案:

答案 0 :(得分:0)

多个问题:

int getIntegers()不会返回任何值。代码不会在a[]中保存任何内容。数组限制未强制执行。

评论代码不会检查fscanf()的返回值。

fscanf()返回0时,代码需要占用1个字符,然后重试。

fscanf(fp, "%d", &a[i])返回0时,表示输入不是数字fscanf()没有使用任何非数字输入。所以请阅读1个字符并重试。

#include <stdio.h>
#define N 100

int getIntegers(char *filename, int a[], int n);

int main(void) {
  FILE *fp;
  char file[] = "random.txt";
  fp = fopen(file, "w");
  if (fp == NULL) {
    fprintf(stderr, "Unable to open file for writing\n");
    return -1;
  }
  fprintf(fp, "1 2 -34 56 -98 42516547example-34t+56ge-pad12345\n");
  fclose(fp);

  int a[N];
  int i;
  int n = getIntegers(file, a, N);

  puts("found numbers:");
  for (i = 0; i < n; i++) {
    printf("%d ", a[i]);
  }
  putchar('\n');

  return 0;
}

int getIntegers(char *filename, int a[], int n) {
  int i;
  FILE *fp = fopen(filename, "r");
  if (fp) {
    for (i = 0; i < n; i++) {
      int cnt;
      do {
        cnt = fscanf(fp, "%d", &a[i]);
        if (cnt == EOF) { fclose(fp); return i; }
        if (cnt == 0) fgetc(fp);  // Toss 1 character and try again
      } while (cnt != 1);
      // printf("%d ", i);
    }
    fclose(fp);
  }
  return i;
}

输出

found numbers:1 2 -34 56 -98 42516547 -34 56 12345