我有一个另存为函数,我需要我的程序来识别文件名并将其与文件扩展名分开。我读过了 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;
}
答案 0 :(得分:0)
以下行是正确的:
char filename;
char fileext;
printf("Filename:\t");
scanf("%s", &filename);
filename = strtok(filename, ".");
fileext = strtok(NULL, ".");
然而strtok
返回char*
,您已将filename
和fileext
声明为单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;
}