0

我有一个另存为功能,我需要我的程序识别文件名并将其与文件扩展名分开。我已阅读 提取文件的扩展名, 但我的另存为功能不是主要功能,因此我不能使用 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;
}
4

2 回答 2

0

以下几行是正确的:

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

但是strtok返回char*并且您已将filenameand声明fileext为 single char。另请注意,应该有与filename缓冲区关联的内存。将其更改为:

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

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

于 2013-10-27T20:10:14.750 回答
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;
}
于 2013-10-27T20:11:05.360 回答