c - 如何在C中将混合数据类型的文件读入字符串

标签 c file input

我正在尝试读取格式如下示例的文件:

3 3 1.5 50
0 2 46.0 0
* 1 46.0 1
2 * 46.0 0
0 0 50.0 0 
* * 42.0 0
2 2 36.1
2 1 42 0
0 1 48.0 0
1 0 48 0

首先,我想将文件的内容存储在字符串中。然后,我想扫描字符串并查看是否有星号*。由于某种原因,我无法将其存储为字符串。每当我尝试打印字符串时,它都会给我空行。有没有一种简单的方法可以从文件中读取数据并将其存储到字符串中?稍后我会将数值数据转换为数组。

代码片段:

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

int main(int argc, char *argv[]){ 

  FILE *id; //Input Data
  double *detect; 
  int nx, ny, i, j, k, n, count, t, frequency;
  double a;
  char val;

  n = 0;

  id = fopen(argv[1], "r");
  frequency = atoi(argv[2]);

 if(id){
   fscanf(id, "%d %d %lf %d", &nx, &ny, &a, &tn);
  }

  detect = (double *) malloc(nx*nx*4*sizeof(double)); 

  if(id){
    for(i=0; i<2; i++){
      fscanf(id,"%s", (detect+i));
    }
  }  


//~ The rest of the code is left out ~


return 0;
}

最佳答案

您可以将数据放入这样的字符串中。

它使用以下内容:

  1. fgets从文件中读取每一行并将其存储在字符串缓冲区中。
  2. malloc在堆上为字符串、char *detect 分配空间。用途realloc在需要时重新分配更多空间。
  3. strcatbuffer 附加到指针 *detect
  4. free释放malloc()请求的内存。

代码:

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

#define BUFFSIZE 100
#define STARTSIZE 10

int
main(int argc, char *argv[]) {
    FILE *id;
    char *detect;
    char buffer[BUFFSIZE];
    size_t slen, currsize = STARTSIZE, len = 0;
    const char *separate = " ";

    id = fopen(argv[1], "r");
    if (!id) {
        fprintf(stderr, "%s\n", "Error reading file");
        exit(EXIT_FAILURE);
    }

    detect = malloc(currsize * sizeof(*detect));
    if (!detect) {
        printf("Error allocating memory\n");
        exit(EXIT_FAILURE);
    }


    *detect = '\0';
    while (fgets(buffer, BUFFSIZE, id) != NULL) {
        slen = strlen(buffer);
        len += slen-1;
        if (slen > 0) {
            if (buffer[slen-1] == '\n') {
                buffer[slen-1] = '\0';
            } else {
                printf("Error: Exceeded Buffer length of %d.\n", BUFFSIZE);
                exit(EXIT_FAILURE);
            }
        }

        if (currsize == len) {
            currsize *= 2;
            detect = realloc(detect, currsize * sizeof(*detect));
            if (!detect) {
                printf("Error reallocating memory\n");
                exit(EXIT_FAILURE);
            }
        }

        strcat(detect, separate);
        strcat(detect, buffer);
    }

    printf("Your string = %s\n", detect);

    free(detect);

    return 0;
}

关于c - 如何在C中将混合数据类型的文件读入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41117648/

相关文章:

C - 使用 extern 访问全局变量。案例分析

javascript - 图片转Base64

python - 将文件中的句子转换为列表中的单词标记

javascript - 使用javascript将选择框转换为输入

c - 在 c 中嵌入 python 时,什么会导致此错误 ("ImportError:No module name site")?

c - Windows 和 UTF-8 字符上的 MinGW + GCC

c - 段错误 - 打开二进制文件

javascript - 如何使用数据集值更新输入字段?

html - 如何在不使用 JS/jQuery 的情况下使占位符消失?

c - 在进程的内核空间中 kmalloc 优先于数组