Question

I am very new with c and less experienced with any other language :/ For an assignment at uni, I am a little stuck on this small part. Essentially I am required to write a 'ls' function that has 4 optional arguments, for example:

list [-l] [-f] [pathname] [localfile] 

Now, the first two are straight forward. To make things more difficult, the 'localfile' doesn't necessarily exist and the 'pathname'(if given) will be located on the server I'm connecting to through a socket (so checking if it is a file is out and checking the pathname is out). I was thinking, check last 4 chars in the string for a '.txt' or something similar. I'm actually completely stumped and will present this problem to my course conveyor tomorrow, if I can't find a solution.

This is a very small part of what I actually have to do but any push in the right direction would be appreciated.

Was it helpful?

Solution

You will need to process argc and argv to get your command line arguments. That is the first thing to work on, getting the arguments - ensuring they are correct, and determining what is being asked for.

int main(int argc, char  *argv[])

Assuming your are on Linux/Unix, you will need to use the directory functions opendir()/readdir()/closedir() - dirent.h. The stat() function will be required to satisfy the -l requirement. access() will determine if a file exists and then stat() will tell you if the file is a regular file or a directory.

I'd make a struct to hold the four optional arguments and return it from a function called "process_arguments" that takes argc and argv as parameters.

struct args {
  bool valid;
  bool l_option;
  bool f_option
  char directory[200]; 
  char filename[200];
}

With the requirement for a socket connection you will have to write a "server program" that will be constantly running on the server and a "client program" that it will fork to handle the requests from your local program. Try and locate examples of socket programs.

Another check for whether you have a path string or a filename is to look for the path separator character - '/' if the server is Unix/Linux. This scheme shouldn't have any path separators in filenames, so the presence of one tells you it is a path.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top