.
carbonize.co.ukcarbonize.co.uk

Y!Tunnel
Trillian
YahELite
Opera
Ad Aware
Ultraedit
YahSEek

Advertisements:


Send honey to your loved ones

[Get Opera!]

Synfire's Guide to C Programming
9. File I/O

        Reading from and writting to a file is a very important aspect of programming in C. Even more so on *nix systems, because everything in *nix is a file. As you will learn in '12. sockets' even the internet is a file! but that is later on. Here you will learn how to read, write and append to a textfile.

TEXTFILES -

Reading.c
-----------------------------------
#include <stdio.h>
#define MAX 1000

int main()
{
	FILE *f;
	/* creates a stream */

	char *string(MAX);
	f = fopen("filename", "r");
	/* links the stream to'filename' in 'r' (read) mode. */

	if(!f) /* if the stream isn't connected to the file */
		return(1); /* exit program */

	while( fgets(string, MAX, f) != NULL)
		printf("%s", string);
	/* creates a while loop and uses fgets to read from 'f' into
	   'string' until it reaches a '\0' or the MAX length. */

	fclose(f);
	/* closes the stream */

	return(0);
}
--------------------------------------
Writing.c
--------------------------------------
#include <stdio.h>

int main()
{
	FILE *f;
	/* creates the stream */

	char *String[] = "This text will be written.";

	f=fopen("filename","w");
	/* opens the file in distructive write mode.
	   Distructive write mode means that if the 
	   file exists then it is overwritten, if it
	   don't exist then it is created. */

	if(!f)  /* checks to see if all went well */
		return(1);

	fprintf(f, "%s\n", String);
	/* writes the contents of 'String' followed by
	   a newline into 'filename'. */

	fclose(f);
	return(0);
}
-----------------------------------------
Appending.c
-----------------------------------------
#include <stdio.h>

int main()
{
	FILE *f;
	/* creates the stream */

	char *string[] = "This is appended to the end of the file.";

	f=fopen("filename","a");
	/* opens the file in APPEND mode. Append writes to the
	   end of the document. */

	if(!f) /* checks to see if went well */
		return(1);

	fprintf(f, "%s\n", string);
	/* writes 'string' to the end of the file */

	fclose(f);
	return(0);
}
---------------------------------------
        Now those examples should suffice for reading and writing to TEXT FILES. Thats all for this first part. Now we go on to structs the reason I have left out binary file manipulations is that honestly it goes beyond the scope of this document. But to make up for it, I am adding a socket section to the end. What can I say, I hate trying to explain binary files.


Back to top | Contact me