【问题标题】:Iterating with fopen in C在 C 中使用 fopen 进行迭代
【发布时间】:2015-01-18 03:38:41
【问题描述】:

这是我的第一个 C 程序 - 我试图每 3 秒在我的桌面上创建一个新的文本文件(称为 0.txt - 999.txt)。这是我目前所拥有的:

#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main() {

  int i;
  char txt_files[1000];

  for (i = 0; i < 1000; i++) {

    sprintf(txt_files, "%d.txt", i);
    puts(txt_files);

    FILE *f;
    f = fopen("~/Desktop/" + txt_files, "w"); 
    fprintf(f, "Testing..\n");

    sleep(3); 

  }
}

我尝试过使用 fopen 多种方式,但我不知道如何将它传递给正确的路径。我认为它应该是“~/Desktop/txt_files[i]”,但这不起作用。谷歌搜索后,我发现了如何使用 sprintf 来格式化文件名,但我不知道如何在 fopen 中使用它。有任何想法吗?

【问题讨论】:

  • fopen 不明白 ~ - 只有 shell 可以。您必须使用实际路径。

标签: c


【解决方案1】:

您几乎是对的,您使用sprintf() 函数从数字生成字符串,您没有想到生成整个文件名吗?

这是我修复的

  1. 使用snprintf()生成完整的文件路径,我更喜欢snprintf(),因为它可以防止缓冲区溢出。

  2. HOME环境变量中获得home路径,~被shell扩展,但不能在c程序中用于扩展$HOME

  3. 添加了对fopen() 调用的检查,在尝试写入文件之前,您应该确保文件确实已打开。

  4. 在写入文件后添加了一个缺失的fclose()

这是您的代码的固定版本

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    int i;
    char filename[256];
    const char *home;

    home = getenv("HOME");
    if (home == NULL)
    {
        fprintf(stderr, "could not read env variable $HOME\n");
        return -1;
    }

    for (i = 0 ; i < 1000 ; i++)
    {
        FILE *file;

        snprintf(filename, sizeof(filename), "%s/Desktop/%d.txt", home, i);
        puts(filename);

        file = fopen(filename, "w");
        if (file != NULL)
        {
            fprintf(file, "Testing..\n");
            fclose(file);
        }
        else
            fprintf(stderr, "could not create the file...\n");
        sleep(3);
    }

    return 0;
}

【讨论】:

    【解决方案2】:

    我认为您需要string.h 中的strcat 函数来生成完整的文件路径。
    我知道 + 运算符可以在 Python 中合并字符串。但据我所知,C 不支持这一点。

    char file_path[1000]; // or just char file_path[1000] = "~/Desktop/"?
    file_path[0] = '\0';
    strcat(file_path, "~/Desktop/");
    strcat(file_path, txt_files);
    f = fopen(file_path, "w");
    

    此外,你应该使用fclose函数在一些操作后关闭文件。

    【讨论】:

    • 你必须鼓励新程序员的良好实践,如果你这样做,你会发现软件中的错误会少得多,那会很棒。显然,许多错误来自许多程序员故意编写不安全代码这一事实。为每个可能的无效指针操作添加检查,可以避免很多麻烦。
    • strcpy "~/Desktop/" 简单地转换为file_path 而不必将第一个字符设置为'/0' 会更有意义
    • @Namfuak 不,因为 OP 无论如何都会使用 sprintf() 函数从整数生成字符串,那么为什么不使用它来生成完整的字符串呢?看我的回答。虽然当然 1 strcpy() + 1 strcat() 比 2 strcat()s 更有意义
    • @iharob 谢谢你的建议,我也是一个新程序员。
    • @Namfuak 由于您的评论,我知道另一个 str 函数。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多