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

标签 c file-io

我的第一篇文章 :),我从 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/

相关文章:

c - 未获得三元运算符的预期输出

c - 内存分配阈值(mmap 与 malloc)

c# - 将 DiskIndex 映射到卷标

php - 如何使用 php/.htaccess 文件从 mysql 数据库中获取文件名来提供文件夹中的文件?

c - 编程器错误

c++ - 在Solaris 上使用-D_FILE_OFFSET_BITS=64 时出现lseek 错误

c - 释放指针时中止陷阱

c - K&R 的这个例子有什么问题?

python - 使用python计算文件中单词之间的空格数?

Python 不识别目录 os.path.isdir()