I have to split up a command line ar开发者_StackOverflowgument in order to determine the file type. In order to do this, I'm using
char fileName; //global variable, just below function prototypes
char *fileType;
fileType= strtok(inputFile, "."); //first string split
fileName= (int) &fileType; //store the file name for further use
fileType= strtok(NULL, "."); //get the file type
The tokenizer function is working, but in the interest of keeping redundant code to a minimum, I want to store the filename, as I will have to create a new file with the same name, but different extension later on.
In the debugger, the the fileName variable never gets used. Why?
About
char fileName; //global variable, just below function prototypes
if fileName
is supposed to be a string then it must be a pointer to the first char
in that string (i.e. char *fileName
).
if fileName
is suposed to be a pointer to a string, then it should be declared as char **fileName
.
About
char *fileType;
if this is a local variable, and fileName
is a pointer to it, then after the function return it will be destroyed and the pointer will point to unknown data.
About
fileName= (int) &fileType; //store the file name for further use
this seem non-sense to me. Why cast the address of fileType
to an integer? I guess the compiler complained because fileName
is a char
and not a char *
and you noticed this would fix the error. Don't do this kind of fixes without understanding what you're doing, because programming like that just leads to esoterical code which must probably won't work as intended anyway.
So, if fileName
is defined as char *
then just do fileName = fileType
. Else, if fileName
is declared as char **
then do fileName = &fileType
;
About
fileType= strtok(NULL, "."); //get the file type
if strtok()
can return a pointer to a new string, and fileName
is declared as char *
, then whatever you stored previously in it wouldn't be meaningful anymore. In this case fileName
would need to be a char **
(a pointer to a string) which I proposed in my first comment.
You need to use a char
array along with strcpy
.
Like this:
#define MAX_FILENAME_SIZE 200
char fileName[MAX_FILENAME_SIZE];
int f()
{
fileType = strtok(inputFule, ".");
// then use strcpy
strcpy(fileName, fileType);
}
A char
global would only store one character.
精彩评论