Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Copy files

Status
Not open for further replies.

FredrikN

Programmer
Joined
Jan 5, 2001
Messages
60
Location
SE
Hi.
I'm new to C and I have a little problem.

I want to take an argv from the command line , (running Linux) and then take the argv and use it in an file movment.

The code looks like this

main (int argc, char *argv[])

file = (mv argv[1] -> newfile.txt)


The last line is the problem.
I don't know how to insert the argv[1]

Lets say I run the program

program 123.txt [enter]

the program vill now move file 123.txt to newfile.txt


Maybe someone know ?

Thanks
 
Use something like this, but make it more robust by specifying directory paths and handling potential command failures:
Code:
main(int argc, char *argv[])
{
  if (argc >= 2)
  {
    char sCommand[512];
    sprintf(sCommand, "mv %s, %s", argv[1], "newfile.txt");

    system(sCommand);
  }
}
 
Fredrik:

If the mv fails, send stderr to /dev/null. Remove if you don't want it:

Regards,


Ed


include <stdio.h>

int main(int argc, char *argv[])
{
char buffer[80];

if(argc == 1)
{
printf(&quot;usage is program <file name>\n&quot;);
exit (1);
}

sprintf(buffer, &quot;mv %s %s %s &quot;, argv[1], &quot; newfile.txt&quot;, &quot;2> /dev/null&quot;);

if((system(buffer) != 0))
printf(&quot;mv failed!\n&quot;);

}
 
Thanks both of you.
Works fine now

//Fredrik
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top