简体   繁体   English

C 中的 fscanf textfile.txt 变量定义

[英]variable definition by fscanf textfile.txt in C

I have a textfile.txt containing variable definitions line by line, eg length = 1.1m我有一个 textfile.txt 包含逐行变量定义,例如长度 = 1.1m

Using fscanf I want to store in my variable double length the value 1.1使用fscanf我想将值 1.1 存储在我的可变double length

Can someone give me some hints how to use fscanf in this case having a '=' seperator?有人可以给我一些提示,在这种情况下如何使用 fscanf 有一个 '=' 分隔符?

Thanks in advance!提前致谢!

Edit: Here is an exemplary inputfile.txt showing its structure:编辑:这是一个示例 inputfile.txt 显示其结构:

[elements]
Number of elements = 2
length_1 = 1.5m
length_2 = 2.1m
velocity_1 = 0.35m/s
velocity_2 = 0.11m/s

[cells]
Number of cells = 2
cell_1 = 0.0m
cell_2 = 1.3m

I want to extract the parameters of both sections to two different structs.我想将两个部分的参数提取到两个不同的结构中。

A simple program to read a formatted file:一个读取格式化文件的简单程序:

#include <stdio.h>

int main(void) {
    FILE *fp = fopen("data.txt", "r");
    float length;

    if (fp == NULL) {
        printf("The file was failed to open.\n");
        return -1;
    }

    while (fscanf(fp, "%*s %*s %f", &length) == 1)
        printf("%f", length);

    return 0;
}

Notice that we've used请注意,我们使用了

%*s %*s %f

format %*s string skips the word from reading it.格式%*s字符串会跳过阅读该单词。

The file data.txt looks something like:文件data.txt类似于:

length = 5.324325m

Then you will get an output of:然后你会得到一个 output :

5.324325

You can now clearly see the strings are truncated and the value is successfully assigned to the variable.您现在可以清楚地看到字符串被截断并且值已成功分配给变量。

Assuming if your text file is something like this:假设您的文本文件是这样的:

length = 1.2m
length = 3.4m
length = 12.4m

Then you can read it using this code:然后您可以使用以下代码阅读它:

FILE* filePtr = fopen("textfile.txt","r"); 
if (filePtr==NULL) 
{ 
    printf("no such file."); 
    return 0; 
} 
  
float num; 
while (fscanf(filePtr,"length = %f", &num)==1) 
    printf("%f\n", num);
fclose(filePtr);

For more information for reading from file, check this link有关从文件读取的更多信息,请查看此链接

Here a way to do, the two sections can be given in any order, or only one can be given, or even none:这里有一个办法,可以按任意顺序给出两个部分,也可以只给出一个,甚至不给出:

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

typedef struct Element {
  double length;
  double velocity;
} Element;

void * read_section(FILE * fp, const char * what, int * n, size_t sz)
{
  if (*n != 0) {
    fprintf(stderr, "invalid file, several sections [%s]\n", what);
    exit(-1);
  }

  char fmt[64];
  
  sprintf(fmt, " Number of %s = %%d", what); /* notice space at beginning */

  if (fscanf(fp, fmt, n) != 1) {
    fprintf(stderr, "invalid file, expected 'Number of %s = <n>'\n", what);
    exit(-1);
  }
  
  if (*n <= 0) {
    fprintf(stderr, "number of %s must be > 0\n", what);
    exit(-1);
  }
  
  void * r = malloc(*n * sz);
  
  if (r == NULL) {
    fprintf(stderr, "not enough memory for %d %s\n", *n, what);
    exit(-1);
  }
  
  return r;
}

void read_var(FILE * fp, const char * var, const char * unity, int rank, double * v)
{
  char fmt[64];
  
  sprintf(fmt, " %s_%d = %%lg%s", var, rank, unity); /* notice space at beginning */
  
  if (fscanf(fp, fmt, v) != 1) {
    fprintf(stderr, "invalid file, expected '%s_%d = <val>%s'\n", var, rank, unity);
    exit(-1);
  }
}

int main(int argc, char ** argv)
{
  if (argc != 2) {
    fprintf(stderr, "Usage: %s <file>\n", *argv);
    exit(-1);
  }
  
  FILE * fp = fopen(argv[1], "r");
  
  if (fp == NULL) {
    perror("cannot open file");
    exit(-1);
  }
  
  int nelts = 0;
  Element * elts = NULL;
  int ncells = 0;
  double * cells = NULL;
  char line[32];
  int i;
  
  while (fscanf(fp, " %31s", line) == 1) { /* notice space at beginning of format */
    if (!strcmp(line, "[elements]")) {
      elts = read_section(fp, "elements", &nelts, sizeof(*elts));
      for (i = 0; i != nelts; ++i)
        read_var(fp, "length", "m", i+1, &elts[i].length);
      for (i = 0; i != nelts; ++i)
        read_var(fp, "velocity", "m/s", i+1, &elts[i].velocity);
    }
    else if  (!strcmp(line, "[cells]")) {
      cells = read_section(fp, "cells", &ncells, sizeof(*cells));
      for (i = 0; i != ncells; ++i)
        read_var(fp, "cell", "m", i+1, &cells[i]);
    }
    else {
      fputs("invalid file, section header expected\n", stderr);
      exit(-1);
    }
  }
  
  fclose(fp);
  
  /* to check */
  
  printf("%d elements:\n", nelts);
  for (i = 0; i != nelts; ++i)
    printf("%d) length=%g, velocity=%g\n", i, elts[i].length, elts[i].velocity);
  
  printf("\n%d cells:", ncells);
  for (i = 0; i != ncells; ++i)
    printf(" %g", cells[i]);
  putchar('\n');
  
  free(elts);
  free(cells);
  
  return 0;
}

Notice the space at the beginning of the formats when it is needed to bypass newlines (and possible other spaces).当需要绕过换行符(以及可能的其他空格)时,请注意格式开头的空格。

Compilation and executions with your example:使用您的示例进行编译和执行:

pi@raspberrypi:/tmp $ gcc -g -Wall x.c
pi@raspberrypi:/tmp $ 
pi@raspberrypi:/tmp $ cat f1
[elements]
Number of elements = 2
length_1 = 1.5m
length_2 = 2.1m
velocity_1 = 0.35m/s
velocity_2 = 0.11m/s

[cells]
Number of cells = 2
cell_1 = 0.0m
cell_2 = 1.3m
pi@raspberrypi:/tmp $ ./a.out f1
2 elements:
0) length=1.5, velocity=0.35
1) length=2.1, velocity=0.11

2 cells: 0 1.3
pi@raspberrypi:/tmp $ 

exchanging section order交换部分顺序

pi@raspberrypi:/tmp $ cat f2
[cells]
Number of cells = 2
cell_1 = 0.0m
cell_2 = 1.3m
[elements]
Number of elements = 2
length_1 = 1.5m
length_2 = 2.1m
velocity_1 = 0.35m/s
velocity_2 = 0.11m/s
pi@raspberrypi:/tmp $ ./a.out f2
2 elements:
0) length=1.5, velocity=0.35
1) length=2.1, velocity=0.11

2 cells: 0 1.3
pi@raspberrypi:/tmp $ 

only elements只有元素

pi@raspberrypi:/tmp $ cat f3
[elements]
Number of elements = 2
length_1 = 1.5m
length_2 = 2.1m
velocity_1 = 0.35m/s
velocity_2 = 0.11m/s

pi@raspberrypi:/tmp $ ./a.out f3
2 elements:
0) length=1.5, velocity=0.35
1) length=2.1, velocity=0.11

0 cells:
pi@raspberrypi:/tmp $ 

only cells只有细胞

pi@raspberrypi:/tmp $ cat f4
[cells]
Number of cells = 2
cell_1 = 0.0m
cell_2 = 1.3m
pi@raspberrypi:/tmp $ ./a.out f4
0 elements:

2 cells: 0 1.3
pi@raspberrypi:/tmp $ 

empty input file空输入文件

pi@raspberrypi:/tmp $ ./a.out /dev/null
0 elements:

0 cells:
pi@raspberrypi:/tmp $ 

more elements and cells更多元素和单元格

pi@raspberrypi:/tmp $ cat f
[elements]
Number of elements = 3
length_1 = 1.5m
length_2 = 2.1m
length_3 = 1.1m
velocity_1 = 0.35m/s
velocity_2 = 0.11m/s
velocity_3 = 0.33m/s

[cells]
Number of cells = 5
cell_1 = 0.0m
cell_2 = 1.3m
cell_3 = 2.3m
cell_4 = 3.3m
cell_5 = 4.3m
pi@raspberrypi:/tmp $ ./a.out f
3 elements:
0) length=1.5, velocity=0.35
1) length=2.1, velocity=0.11
2) length=1.1, velocity=0.33

5 cells: 0 1.3 2.3 3.3 4.3
pi@raspberrypi:/tmp $ 

and the possible error cases are checked, I encourage you to never suppose all is always ok but to check it is并且检查了可能的错误情况,我鼓励您永远不要认为一切都很好,但要检查它是

To finish if you are under Linux/Unix check your program running under valgrind , for instance:如果您在 Linux/Unix 下完成,请检查您在valgrind下运行的程序,例如:

pi@raspberrypi:/tmp $ valgrind ./a.out f
==13981== Memcheck, a memory error detector
==13981== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==13981== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==13981== Command: ./a.out f
==13981== 
3 elements:
0) length=1.5, velocity=0.35
1) length=2.1, velocity=0.11
2) length=1.1, velocity=0.33

5 cells: 0 1.3 2.3 3.3 4.3
==13981== 
==13981== HEAP SUMMARY:
==13981==     in use at exit: 0 bytes in 0 blocks
==13981==   total heap usage: 5 allocs, 5 frees, 5,560 bytes allocated
==13981== 
==13981== All heap blocks were freed -- no leaks are possible
==13981== 
==13981== For lists of detected and suppressed errors, rerun with: -s
==13981== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
pi@raspberrypi:/tmp $ 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM