gpt4 book ai didi

c - 在 C 中使用 fopen 进行迭代

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:36 25 4
gpt4 key购买 nike

这是我的第一个 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 中使用它。有任何想法吗?

最佳答案

你几乎做对了,你使用 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;
}

关于c - 在 C 中使用 fopen 进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28006901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com