LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Quick C question (https://www.linuxquestions.org/questions/programming-9/quick-c-question-542072/)

Komelore 03-31-2007 12:14 AM

Quick C question
 
Hey everyone!
Im trying to write a program in C that makes a copy of another file. Im having problems so far.
Quote:

#include <stdio.h>
main()
{
int c;
FILE *IPFile;
FILE *OPFile;


IPFile = fopen("/home/$USER/Desktop/examplefile.txt","r");
OPFile = fopen("/home/$USER/backup/(randomname)","w");


while ((c = fgetc(IPFile)) != EOF)
{
fputc(c, OPFile);
}

fclose(IPFile);
fclose(OPFile);
}
I would really like to figure out a way to generate random names and use it in place of the actual file name. I know its inefficient but i'm trying to learn. As an example...I dont know why something like this doesnt work
Quote:

int x
x = (some value)
(and then at the OPFILE part...)
OPFile = fopen("/home/$USER/backup/%s",x,"w");
I tried stuff like that with random numbers but it gives me this error:
Quote:

warning: passing arg 2 of `fopen' makes pointer from integer without a cast
error: too many arguments to function `fopen'
Thanks in advance.

acid_kewpie 03-31-2007 01:41 AM

you'd use sprintf to convert the integer into a formatted string. eg...

sprintf (filename, "myfile%d.txt", x);
fopen(filename);

graemef 03-31-2007 01:44 AM

you need to convert the integer you had from the random number you generated to a string. You can do this using a function such as sprintf, check out man sprintf...

Quigi 04-02-2007 03:28 PM

By the way, use [ code ] instead of [ quote ] for code samples, to keep the indentation.


All times are GMT -5. The time now is 06:38 AM.