【问题标题】:Using a variable file name in C to read from multiple files with similar names?在C中使用变量文件名从多个具有相似名称的文件中读取?
【发布时间】:2015-11-29 02:23:20
【问题描述】:

我有多个名为 sensor0.txt、sensor1.txt、sensor2.txt 等的文件。我需要打开这些文件,对它们进行计算,然后将它们打印在屏幕上。

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

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
 }

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

【问题讨论】:

    标签: c file syntax


    【解决方案1】:
    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);
       }
    }
    

    【讨论】:

    • 谢谢我不知道这个 sprintf 函数你的解释非常清楚和感激! ^^
    • @JoelBay:欢迎来到 Stack Overflow!请阅读(简短!友好!)介绍性tour。没有必要,甚至略微皱眉,使用 cmets 只是为了感谢您的回答。请阅读What should I do when someone answers my question?
    【解决方案2】:

    使用 sprintf 函数来创建您的文件名。例如:sprintf(filename, "%s%d.txt", "sensor", number)。之后,正常打开这个名字的文件

    【讨论】:

    • 为什么在这里使用%s?将任意输入写入printfsprintf 可以被视为“不安全”,但这肯定不是不可变字符串“sensor”的问题吗?
    猜你喜欢
    • 2015-12-04
    • 2023-03-15
    • 2016-12-27
    • 2021-10-09
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    • 2023-03-26
    相关资源
    最近更新 更多