简体   繁体   中英

how to check if there's a string in the command line

I have this command line:> write_strings "Hello World!" a.txt b.txt dir/a.txt. all the elements (command, string, file names) go into an array of char pointer. how can I take an element and check if it's a string or a file name? I don't mean the exact code lines, buts just need the idea. the program should return an error if there's no string.

You can use an API such as stat or access to check if the file pointed to by a path exists. There is no fundamental distinction between filepaths and regular strings when they are passed to your process.

If you're using the standard main(int argc, char *argv[]) convention, you can loop through argv , checking each one to see if it's a file via one of the previously-mentioned system calls.

Every string that can be passed on a command line is a potential pathname, since the only restriction in both cases is that there can't be any NULs.

A program with a command line syntax in which a specific argument might or might not be used as a pathname (depending on some vague definition of "filename-ish strings" or even a file existence test) is a bad design. Each argument should have a meaning defined by its order in the argument list, or by being associated with an option like -m msg or -o outputfile .

A well-behaved unix program will let the user create a file called Hello world! if he wants.

not regarding how meaningful the program might or might not be - you can compare the single characters of your char *argv[] by looping through them via argv[i][j] . If every string includes a ".txt" you do not have a string, which is not a filename in your context

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM