简体   繁体   English

C的文件扩展名作为用户输入

[英]File extensions in C as user input

I have a save as function and I need my program to recognise and separate the file name from the file extension. 我有一个另存为功能,我需要我的程序来识别文件名并将其与文件扩展名分开。 I have read Extracting the extension of a file but my save as function is not main, so I can not have argv[1]. 我已经阅读了提取文件的扩展名,但是我的另存为函数不是main,所以我不能使用argv [1]。 Here is my full code so far: 到目前为止,这是我的完整代码:

#include <stdio.h>
#include <errno.h>

void save_as()
{
    // user enters their desired name for the file
    char filename;
    char fileext;
    printf("Filename:\t");
    scanf("%s", &filename);
    filename = strtok(filename, "."); // according to the link I mentioned above this should have been: filename = strtok(argv[1], ".");
    fileext = strtok(NULL, ".");
}

int main()
{
    save_as();
    return 0;
}

Following lines are correct: 以下几行是正确的:

char filename;
char fileext;
printf("Filename:\t");
scanf("%s", &filename);
filename = strtok(filename, ".");
fileext = strtok(NULL, ".");

however strtok returns char* and you have declared filename and fileext as single char . 但是strtok返回char*并且您已将filenamefileext声明为单个char Also note that there should be memory associated with the filename buffer. 另请注意,应该有与filename缓冲区关联的内存。 Change it to: 更改为:

char filename[255];
printf("Filename:\t");
scanf("%254s", &filename);
filename = strtok(filename, ".");
char* fileext = strtok(NULL, ".");

Also consider checking the return value of these calls as some error might occur. 还可以考虑检查这些调用的返回值,因为可能会发生一些错误。

You can have argv[1]: 您可以拥有argv [1]:

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

void save_as(char *filename)
{
    // user enters their desired name for the file
    char *fileext;

    filename = strtok(filename, "."); // according to the question I mentioned above this should have been: filename = strtok(argv[1], ".");
    fileext = strtok(NULL, ".");
}

int main(int argc, char **argv)
{
    if(argc != 2)
    {
       printf("usage: myprogram myfile.myextension");
       return 0;
    }
    save_as(argv[1]);

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM