Welcome to pickSourcecode.com Login | Register    
pickZy.com
 Home  | search  | games  | General  | C  | C++  | Java  | Php  | Networking  | Visual Basic  | VC++  | Win32  | MFC  | JavaScript  | Jobs  | JavaScript  | Post jobs
Writing to Files Using fwrite       Share
2010-02-03 |  TestNameTR  | Viewed: 742  |    1

Writing to Files Using fwrite

This function has the same four arguments to fread:

The first is a char * variable and is what you want to write into a file.

The second is the size of char, i.e. 1.

The third is the number of characters to write - this does come into effect when passing a char * as opposed to a char array.

Finally, the last argument is the FILE pointer to the file to write to.

This example is saved as file.c - it opens file.c for reading, and copies the content into file2.c

Afterwards, it'll open file2.c and display the source code on the screen, including the comments!

Notice I used two FILE pointers - one for the reading, the other for the writing.

#include <stdio.h>

int main() {
FILE *sourceFile;
FILE *destinationFile;
char *buffer;
int n;

sourceFile = fopen("file.c", "r");
destinationFile = fopen("file2.c", "w");

if(sourceFile==NULL) {
printf("Error: can't access file.c.\n");
return 1;
}
else if(destinationFile==NULL) {
printf("Error: can't create file for writing.\n");
return 1;
}
else {
n = fread(buffer, 1, 1000, sourceFile); /* grab all the text */
fwrite(buffer, 1, n, destinationFile); /* put it in file2.c */
fclose(sourceFile);
fclose(destinationFile);

destinationFile = fopen("file2.c", "r");
n = fread(buffer, 1, 1000, destinationFile); /* read file2.c */
printf("%s", buffer); /* display it all */

fclose(destinationFile);
return 0;
}
}

Reference link:
http://irc.essex.ac.uk/www.iota-six.co.uk/c/i4_fwrite_fscanf_fprintf.asp


Latest topics
C - Arrays of structures  Viewed: 285
tcpdump by host name or ip  Viewed: 291
C - structures and functions  Viewed: 292
C - For loop statements  Viewed: 295
C - pointers and Arrays  Viewed: 295
C - File Access  Viewed: 295
C - pointers to pointers  Viewed: 296
C - Register variables  Viewed: 297
C - Static variables  Viewed: 298
C - Pass-by-reference parameters  Viewed: 299

Comments:





Submit comment's

Type:

User Comment's:

Submitted By:
Prof: Software Engineer
Tech: C ,Cpp
Send Mail: ratheesh



Related topics
C - Functions and program structure, Programmed pass-by-reference via pointers, Pass-by-reference parameters
C - Pass-by-reference parameters
C - pass-by-reference via pointers

Related References
c - swap num, pass-by-reference parameters
c - pass-by-reference via pointers

Web site contents © Copyright 2007, All rights reserved.
Help | Terms and Conditions | Privacy Policy | About Us