You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Linux终端读取文本文件内容并创建同名文件夹

两种方法实现读取文本文件创建文件夹(Ubuntu终端)

Hey there! Let's cover both the quick terminal command approach (no coding needed) and fix up that C program you started—either way will get the job done.

方法1:直接用终端命令(最简单)

如果你的in.txt里每行是一个文件夹名称(比如你的例子里只有一行name),这两个方法都能快速创建文件夹:

用xargs命令

这是最简洁的方式,一行命令搞定:

xargs mkdir < in.txt

解释:xargs会读取in.txt的内容,把每一行作为参数传递给mkdir,自动创建对应的文件夹。如果文件里有多个名字(每行一个),它会一次性创建所有文件夹。

用while循环(更灵活,支持带空格的文件夹名)

如果你的文件夹名称可能包含空格或者特殊字符,这个循环更可靠:

while IFS= read -r foldername; do
    mkdir "$foldername"
done < in.txt

解释:

  • IFS= 确保文件夹名称开头或结尾的空格不会被截断
  • read -r 避免把反斜杠等转义字符当成特殊字符处理
  • "$foldername" 用双引号包裹,确保带空格的名称能被正确识别

方法2:修正你的C代码并编译运行

你的原始C代码有语法错误,咱们一步步修正它:

正确的C代码

把下面的代码保存为make_folders.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h> // 用于strchr()函数

int main() {
    // 打开in.txt文件,只读模式
    FILE *file = fopen("in.txt", "r");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    char foldername[256]; // 存储读取到的文件夹名称
    // 逐行读取文件内容
    while (fgets(foldername, sizeof(foldername), file) != NULL) {
        // 去掉fgets读取到的换行符(因为每行末尾会有\n)
        char *newline = strchr(foldername, '\n');
        if (newline != NULL) {
            *newline = '\0';
        }

        // 构建mkdir命令,用双引号包裹名称处理空格
        char command[512];
        snprintf(command, sizeof(command), "mkdir \"%s\"", foldername);
        
        // 执行命令并检查结果
        int exit_status = system(command);
        if (exit_status != 0) {
            fprintf(stderr, "Failed to create folder: %s\n", foldername);
        }
    }

    fclose(file);
    return 0;
}

编译和运行命令

在终端里执行以下命令:

  1. 编译代码:
gcc -o make_folders make_folders.c
  1. 运行生成的程序:
./make_folders

解释:

  • gcc是Ubuntu的C语言编译器,-o make_folders指定生成的可执行文件名为make_folders
  • ./make_folders运行这个程序,它会读取in.txt并创建对应的文件夹

内容的提问来源于stack exchange,提问作者beginner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:00:30