PDA

View Full Version : read & write in C language



hellboy1
February 4th, 2007, 11:22 AM
yo guys i wrote a C program that generates random numbers, but i wanna write those numbers to a file, like a notepad file, but m kinda stuck, i can't figure it out :(, i've been tryin' 2 search all over d net but nah :(

can somebody hook me up?

Templarian
February 4th, 2007, 01:02 PM
http://zamov.online.fr/EXHTML/CSharp/CSharp_302155.html

btw google is your friend.

Ben H
February 4th, 2007, 01:36 PM
Templarian, he said C, not C# ;)

hellboy1, I'm assuming that you're using ANSI C. There is a file pointer datatype which allows us easy access to files. It is defined in stdio.h. To open a file with a file pointer, we use this code:



#include <stdio.h>
int main()
{
/*Let's first of all define our pointer:*/
FILE *fpointer;
/*Next we'll open the file and check that we were able to do so*/
fpointer = fopen("examplefile.txt", "a+");
if ( fpointer == NULL )
{
printf("There has been an error opening your file");
exit(1);
}
}
The fopen function takes 2 arguments. The first is the file name. The second describes how to open the file. I'll assume you don't want to overwrite the contents each time, so we're using read/append mode (a+).

Next we have to write to the file. I'll assume that you know how to use the printf function, as there is another function, called fprintf which is just the same, but there is another argument at the beginning, where you put your file pointer. After that we use fclose, and we're done ;)
The final code:



#include <stdio.h>
int main()
{
/*Let's first of all define our pointer:*/
FILE *fpointer;
int mynum = 15; //You could put your random number into this variable ;)
/*Next we'll open the file and check that we were able to do so*/
fpointer = fopen("examplefile.txt", "a+");
if ( fpointer == NULL )
{
printf("There has been an error opening your file");
exit(1);
}
//Write to the file
fprintf (fpointer, "%d\n", mynum);
//Close the file
fclose (fpointer);
}
Hope that helps you a bit :thumb2:

-Ben