c - 读取文件并只获取整数并继续直到结束

标签 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。然后返回这些数字并在 main 中打印出来。我试过但无法让它工作。我应该/可以做什么才能使它正常工作?或者我做错了什么。

最佳答案

多个问题:

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 

关于c - 读取文件并只获取整数并继续直到结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36143026/

相关文章:

HTTPSresource 的 Excel VBA URLDownloadToFile 错误

java - 如何避免将文件保存在硬盘上?

c - 使用 GetFileVersionInfo 和 VerQueryValue 获取 Windows 10 的完整版本号时出现问题

c++ - Eclipse C++ : "Program "g+ +"not found in PATH"

c - LeetCode : Address Sanitizer Violations

c - 允许用户在文件中搜索单词的程序

c - 对文件的操作

python - Python 和 C 的结果之间的差异

c - Realloc 搞乱了代码

PHP 创建随机 tmp 文件并获取其完整路径