c - 如何创建文件名为 argv[1].blabla 的文件?在c中

标签 c file

我知道如何创建文件,但无法创建扩展名为 .blabla 的文件。这不可能吗?

谢谢

最佳答案

您可以使用固定长度和 snprintf,如 Tim Cooper 所说,或者您可以使用 mallocstring.h 中包含的字符串函数

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

int main(int argc, char *argv[])
{
    #define EXT ".blabla"
    char *s;
    FILE *f;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s filename\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    s = malloc(strlen(argv[1]) + strlen(EXT) + 1);
    if (s == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    strcpy(s, argv[1]);
    strcat(s, EXT);
    f = fopen(s, "w");
    if (f == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    fclose(f);
    free(s);
    return 0;
}

关于c - 如何创建文件名为 argv[1].blabla 的文件?在c中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17445817/

相关文章:

Linux 中的 C++ 简单打开文件对话框

php - 使用 php 向后读取文件行(fgets)

c++ - 没有第二个操作数的三元运算符

c - C 语言文件 I/O 程序 : Segmention Fault (core dumped)

c - 对指针数组进行排序

bash - 如何使用 find 和 Perl 列出文件?

file - 获取文件名和内容,然后用mapreduce合并到另一个文件中

c - sscanf 转换警告 c

c - 如何修复它? CRT 检测到应用程序在堆缓冲区结束后写入内存

perl - 无法重新组合 MP3 数据的分块下载