How can we use structures in C to output the contents of a text file?

In C language, we can use structures and file manipulation functions to output the contents of a text file. The specific steps are as follows:

  1. Create a structure to store data from a file. For example, if each line in a text file contains a string, you can define a structure as follows:
struct Data {
   char line[100];  // 假设每行最多100个字符
};
  1. To open a file
  2. read a line from a file
FILE *file = fopen("input.txt", "r");  // 打开文本文件
struct Data data[100];  // 假设最多100行数据
int i = 0;
while (fgets(data[i].line, sizeof(data[i].line), file) != NULL) {
   i++;
}
fclose(file);  // 关闭文件
  1. Output a formatted string
for (int j = 0; j < i; j++) {
   printf("%s", data[j].line);
}

The complete code is shown below:

#include <stdio.h>

struct Data {
   char line[100];
};

int main() {
   FILE *file = fopen("input.txt", "r");
   struct Data data[100];
   int i = 0;
   while (fgets(data[i].line, sizeof(data[i].line), file) != NULL) {
       i++;
   }
   fclose(file);

   for (int j = 0; j < i; j++) {
       printf("%s", data[j].line);
   }

   return 0;
}

The code above is used to read the contents of a text file named input.txt and output them to the standard output. If you want to output to another file, you can use the fprintf function to write the contents to the file. For specific usage instructions, refer to the documentation for the relevant functions.

bannerAds