在C中使用变量文件名从具有相似名称的多个文件中读取? [英] Using a variable file name in C to read from multiple files with similar names?

查看:40
本文介绍了在C中使用变量文件名从具有相似名称的多个文件中读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个文件,分别名为sensor0.txt,sensor1.txt,sensor2.txt等.我需要打开这些文件,使用它们进行计算,然后在屏幕上打印它们.

I have multiple files named sensor0.txt, sensor1.txt, sensor2.txt and so on. I need to open these files, do calculations with them, and print them on the screen.

所以我想到了类似的东西,

So I thought of something like,

for(i = 0; i < N/*(Number of files)*/; i++)
{
 fpointer = fopen(/*not sure how to format this*/)
 //calculations I need to perform with said file
 //Print results of calculations on the screen
 }

我无法找到直接解决此问题的方法.这有可能吗?或者我必须创建一些数组并存储所有信息,然后使用所有所述存储的信息进行计算.

I can't quite find a straight forward solution to this. Is this even possible? Or must I create some arrays and store all the information, and then do calculations with all of said stored information.

推荐答案

  1. 使用字符数组存储文件名.
  2. 使用 i 的值创建文件的名称.
  3. 在for循环中打开文件并读取内容.

char filename[50]; // Make it large enough
for(i = 0; i < N/*(Number of files)*/; i++)
{
   // Construct the filename.
   sprintf(filename, "sensor%d.txt", i+1);

   // Open the file.
   fpointer = fopen(filename, "r");
   if (fpointer != 0)
   {
      //calculations I need to perform with said file
      //Print results of calculations on the screen
      fclose(fpointer);
   }
}

这篇关于在C中使用变量文件名从具有相似名称的多个文件中读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆