Results 1 to 3 of 3
Thread: read & write in C language
-
February 4th, 2007, 10:22 AM #112Registered User
posts
read & write in C language
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?
-
February 4th, 2007, 12:02 PM #2
http://zamov.online.fr/EXHTML/CSharp/CSharp_302155.html
btw google is your friend.
-
February 4th, 2007, 12:36 PM #3
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:
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+).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); } }
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:
Hope that helps you a bitCode:#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); }
-BenLast edited by Ben H; February 5th, 2007 at 12:51 PM.
If you notice this notice you will notice this notice was inspired by the noticing of another notice.

Reply With Quote


Bookmarks