-
writing stdout to a file
I think the subject of this thread is probably wrong. But basically I've written a program to print out exactly what I wanted to stdout, but having trouble writing to a file.
The codes I have written is slightly different as I have included system() to run a unix command.
Here's a small part of my code (slightly different to my original code to advoid confusions):
char namegen[20000];
for (i=1; i <= 3; i++) {
printf ("%d\t", rand() % 5000);
sprintf( namegen, "cat /dictionaryfile | head -631 | tail -1");
fflush(stdout);
system (namegen);
}
the cat /dictionaryfile | head -631 | tail -1
is a unix command which looks in the file "dictionaryfile" and prints out the 631th word, I have no idea what the tail -1 is hehe, but forget about that
the fflush(stdout) is to synchronise the printf() and system() commands
now what my program can do right now is print 3 random numbers with the 631th word from the dictionary file, eg
235 chicken
224 chicken
446 chicken
each word seperated by a tab
what I want to do now is store these into a file, which I don't really know how to
so far I have
FILE *myfile;
myfile = fopen( "myfile.txt", "w");
and then I've tried using fwrite etc, and don't seem to be able to store the data into the file.
If anyone have any suggestion, please reply :)
Thanks,
Will
-
Maybe the file already exists and only has read permissions, or maybe you are not allowed to create files in that directory? Check if fopen returns a NULL pointer.
You can use the fputs or fprintf function for example to write to a text file. The fwrite function is more used when writing to binary files.
-
You won't be able to trap the output from a system() called program easily. If you're intent on using system(), you could simply redirect your output using > (or >>). Something like:
Code:
cat /dictionaryfile | head -631 | tail -1 >output.file
But this is a pretty nasty way of doing things.
A better way (for the program, and your learning experience) would be to open the dictionary yourself, and find the Nth word. If the dictionary has one word per line, just use fgets() in a loop, and count your way to the Nth line.
Also, your method of getting random numbers is not the best.
-
I'll keep trying to use fputs and fprintf to store the data.
I guess I could also try opening the dictionaryfile up, coz I'm meant to pick random words out of the dictionaryfile which has over 20000 words, and trying to make my program run more efficently.
I'll give
cat /dictionaryfile | head -631 | tail -1 >output.file
a try
just that I don't have any experience writing to a file, and these textbooks ain't helping very much.
Thanks anyway.
Will
-
>>I'm meant to pick random words out of the dictionaryfile which has over 20000 words, and trying to make my program run more efficently.
OK, pseudo code time:
Code:
OpenFile
Counter = 0
While ReadALineInto(InputString) == OK AND Counter < 200
Counter = Counter + 1
End While
print "The magic word is " InputString
CloseFile