【问题标题】:Retrieve information from a file and transfer to another in c in different format从文件中检索信息并以不同格式在 c 中传输到另一个文件
【发布时间】:2020-09-23 03:43:27
【问题描述】:

如何从 file1.txt 中读取这种格式的数据

ID: 123 GPA: 3.39 3.67 4.00
ID: 456 GPA: 2.39 2.67 2.90

然后将file2.txt中的数据转成这种格式:

ID: 123 GPA: 3.39 3.67 4.00 cGPA: 3.69
ID: 456 GPA: 2.39 2.67 2.90 cGPA: 2.65

【问题讨论】:

  • 逐行读取输入,将其解析为单独的数据元素,进行计算,将输入和结果写入新文件,一次一行。你试过什么了?如果您不知道从哪里开始,请咨询您的导师;)

标签: c file copy file-transfer read-write


【解决方案1】:

Kevin Boone 已经说过如何做到这一点,但如果您不知道如何做到这一点,这里有一个简单的程序,我添加了一些 cmets 以使代码清晰

#include <stdio.h>

int main() {
  FILE *f1 = fopen("file1.txt", "r"), *f2 = fopen("file2.txt", "w");
  // check to see if the files have been opened successfully
  if(f1 == NULL || f2 == NULL) {
    printf("There was an error opening the files");
    return 1;
  }
  // store the id and the returned value of successfully matched items of `fscanf`
  int id, x;
  // store the three gpa values as an array of doubles
  double gpa[3], cgpa;
  while(1) {
    // get the data as `int, double, double, double` from the file `file1.txt`
    x = fscanf(f1, "ID: %i GPA: %lf %lf %lf ", &id, &gpa[0], &gpa[1], &gpa[2]);
    if(x == 4) {
      // there is a match and we can do our calculation and write that line to the second file
      cgpa = (gpa[0] + gpa[1] + gpa[2]) / 3;
      // print the line to the file `file2.txt`
      fprintf(f2, "ID: %i GPA: %.2lf %.2lf %.2lf cGPA: %.2lf\n", id, gpa[0], gpa[1], gpa[2], cgpa);
    } else if(x == EOF) {
      // we have read the whole file
      break;
    } else {
      // failed to match
      printf("No match");
    }
  }
  // close the files at the end
  fclose(f1);
  fclose(f2);
  return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多