gpt4 book ai didi

c - C 中的文件 I/O 管理

转载 作者:太空狗 更新时间:2023-10-29 16:13:12 25 4
gpt4 key购买 nike

我的第一篇文章 :),我从 C 语言开始,作为进入编程领域的基本学习步骤。我正在使用以下代码从文本文件中读取字符串,使用该字符串名称创建目录并打开一个文件以写入该创建的目录。但是我无法在 made 目录中创建文件,这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
#include <string.h>

int main()
{
char file_name[25], cwd[100];
FILE *fp, *op;

fp = fopen("myfile.txt", "r");

if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}

fgets(file_name, 25, fp);

_mkdir(file_name);

if (_getcwd(cwd,sizeof(cwd)) != 0)
{
fprintf(stdout, "Your dir name: %s\\%s\n", cwd,file_name);

op = fopen("cwd\\file_name\\mynewfile.txt","w");
fclose(op);
}
fclose(fp);
return 0;
}

最佳答案

您需要在打开前将文件名(带路径)存储在 C 字符串中。您打开的是 cwd\file_name\mynewfile.txt。我怀疑您的目录名为 cwd。示例可能是:

char file_path[150];
sprintf(file_path, "%s\\%s\\mynewfile.txt", cwd, file_name);
op = fopen(file_path,"w");

关于c - C 中的文件 I/O 管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15402393/

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