Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 从文本文件读取的数据为0/Null_C_Text Files - Fatal编程技术网

C 从文本文件读取的数据为0/Null

C 从文本文件读取的数据为0/Null,c,text-files,C,Text Files,我正在写一个C程序,从两个文本文件中读取数据,并将它们合并到一个文本文件中。在读取文本文件时,我会打印这些值,以确保得到正确的值,但所有出现的值不是0就是Null 代码如下: #include <stdio.h> #include <stdlib.h> #include <string.h> #define str_len 100 //Question 2A typedef struct { int atmNum; char name[str_len

我正在写一个C程序,从两个文本文件中读取数据,并将它们合并到一个文本文件中。在读取文本文件时,我会打印这些值,以确保得到正确的值,但所有出现的值不是0就是Null

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define str_len 100

//Question 2A
typedef struct {
  int atmNum;
  char name[str_len];
  char symbol[str_len];
  float atmWeight;
} PeriodocElement;

void SortedMergedFile (FILE *file1, FILE *file2);

int main () {
  FILE *file1;
  file1 = fopen("1.txt", "r");
  FILE *file2;
  file2 = fopen("2.txt", "r");

  if (file1 == NULL) {
    printf("FILE 1 DOES NOT EXIST\n");
  }
  if (file2 == NULL) {
    printf("FILE 2 DOES NOT EXIST\n");
  }
  else {
    SortedMergedFile(file1, file2);
  }
}

void SortedMergedFile (FILE *file1, FILE *file2) {
  PeriodocElement elements [150];
  int i = 0;

  while (i != 4) {
    fscanf(file1, "%d  %s  %s %f", &elements[i].atmNum, elements[i].name, elements[i].symbol, &elements[i].atmWeight);
    i++;

    printf("\n%d %s %s %4.2f", elements[i].atmNum, elements[i].name, elements[i].symbol, elements[i].atmWeight);
  }
}
如果有人能发现我做错了什么,我将不胜感激

  • 您正在阅读
    元素[i]
    的组件
  • 然后增加
    i
  • 然后打印
    元素[i]
    的组件(现在
    i
    大了一个),当然这些组件还没有初始化

  • 尝试打印fscanf的返回值以进行调试。我怀疑格式说明符中的
    ”会造成一些破坏。如果将其替换为
    ,会发生什么情况?例如,一个空白。@Yunnosch My bad,应该是“%d%s%s%f”。我纠正了它,但仍然得到了相同的错误。如果你用非空的、可识别的值初始化数组元素,它们会被打印出来吗?这将意味着fscanf完全失败。@Yunnosch它现在工作了,我在打印之前增加了I。谢谢你的帮助。非常感谢你,我真不敢相信我错过了。
    08  Serium  Se 40.08
    20  Sodium  Na 22.99
    45  gatium  Ga 23.90
    56  Manion  Ma 45.99