问题
Some details
- Language: C
- System: Linux; working with command line (terminal), files are read in through the terminal
- User experience with C: 3 months
I have been trying to extract the extension of a given file for example "myfile.wld", so that later I can make a check to see if the right type of file has been entered at the terminal before I work on the contents of the file. This is necessary for an assignment
I have used the function "strtok" to separate the input into sections by a delimiter "."
dot=strtok(argv[1], ".");
filename=dot;
filename is now the first part of the input "myfile", my question is how can I get to the second part after the ".", please advise, and please be patient enough to make it as simple as possible so that I can make use of your replies
Thanks
回答1:
char *extension;
extension=strtok(NULL, ".");
after your code above.
First, call strtok()
with pointer to str
like this strtok(str, ".")
.
Then keep calling strtok(NULL, ".")
for next token.
When the returned value is null (\0
) then it is end of string.
回答2:
See http://www.cplusplus.com/reference/clibrary/cstring/strtok/
Basically you just need to call strtok again with a NULL pointer. So:
filename = strtok(argv[1], ".");
fileext = strtok(NULL, ".");
回答3:
call strtok
again passing in NULL as the parameter:
extension=strtok(NULL,".")
the first call to strtok
should point to the string you want tokenized. All calls after that should have have NULL as the first parameter, strtok
will return tokens until it has processed the entire string that was passed in during the first call
回答4:
The filename could contain more than one ".": foo.bar.buz for example. With your code you'll get foo and bar.buz instead of foo.bar and buz as expected. The right way is to use something like this:
char *filename = argv[1];
char *ext = strrchr(argv[1], '.');
if (ext) {
*ext = '\0';
ext++;
}
来源:https://stackoverflow.com/questions/8935905/extracting-the-extension-of-a-file