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

时间:2013-10-27 20:06:06

标签: c file strtok

我有一个另存为函数,我需要我的程序来识别文件名并将其与文件扩展名分开。我读过了 Extracting the extension of a file 但我的保存功能不是主要的,所以我不能拥有argv [1]。这是我到目前为止的完整代码:

#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;
}

2 个答案:

答案 0 :(得分:0)

以下行是正确的:

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

然而strtok返回char*,您已将filenamefileext声明为单char。另请注意,应该有与filename缓冲区关联的内存。将其更改为:

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

还要考虑检查这些调用的返回值,因为可能会发生某些错误。

答案 1 :(得分:0)

你可以拥有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;
}