Steve
Steve

Reputation: 596

Open a file in C

I am trying to write a tiny program in C that will open a file and then run the filename in terminal to stream the file to my Apple TV.

The reason I want to do this is so I can right click a media file, select 'Open With', choose 'Apple TV' from the list and then have it stream to my Apple TV via the airstream program.

My code so far is as follows

#include <stdio.h>
#include <string.h>

int main ()
{
   char command[50];

   strcpy( command, "airstream '/home/steve/media.mp4' -o 192.168.0.2" );
   system(command);

   return(0);
}

Very simple, but I'm not sure how to handle a file being passed to the application to allow it to get the filename and modify the command.

Upvotes: 0

Views: 238

Answers (2)

user529758
user529758

Reputation:

(First, let me make a comment on strcpy(): as-is, the call to strcpy() is superfluous (and imposes a security issue), because you are using a constant string. You could have written system("airstream '/home/steve/media.mp4' -o 192.168.0.2") instead.)

If you want to construct a command given a filename, you could in theory write

char command[LINE_MAX];
snprintf(command, sizeof command, "some_command %s", argv[1]);
system(command);

But that again rises a security problem, because now your program can be hijacked to execute an arbitrary external program, by passing it a malformed command-line argument, similarly to an SQL injection attack.

You'd be better off finding the library/API the airstream executable uses, and incorporate that directly into your program. If no such thing exists, you have to make sure to at least validate the user input (i. e. escape special characters, etc.) before handing it over to the shell for execution.

Upvotes: 1

unwind
unwind

Reputation: 399833

You need to use the arguments passed to the main() function. Change the function's signature to:

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

Then loop over the string pointers in argv[], which will be the command-line arguments your program was given.

Upvotes: 1

Related Questions