C files/streams

From wikinotes


fopen

FILE *fd;				// create pointer


fd = fopen(
	"/tmp/file",		// filename
	"w"					// mode
);

fclose( fd );			// close file


fwrite

Writing is fairly standard, it is technically possible to write an array of items (provided they have a uniform size(?)), I am thinking it is going to save me a lot of trouble to write one chunk at a time.

char *name = "my name is will";
fwrite( 
	name,					// pointer to array of items to be written
	sizeof(name),		// size in bytes of each element you are writing
	1,						// number of items to write (each with size of 'size' arg)
	fd,					// pointer to FILE object (file-descriptor)
)


fread

reading from a file is a little more complicated, because you need to know how much you are reading.

cursor position (fseek/ftell)

fseek allows you to change a file-descriptor's position in a file. ftell prints the current position in the file.

fseek(

	fd,			// file descriptor

	0,				/* number of bytes to read from
	             *   0 (move 0 bytes from next-arg)
	             *   5 (5 bytes AFTER  next arg)
	             *  -5 (5 bytes BEFORE next arg)
	             */

	SEEK_END		/* position to read from
					 *
					 *   SEEK_SET (beginning of file)
					 *   SEEK_CUR (current pos of pointer)
					 *   SEEK_END (end of file)
					 */
);
ftell(  fd );	// print current position
rewind( fd );	// reset cursor position to beginning of file

read entire file

#include <stdio.h>
#include <stdlib.h>

FILE *fd;
long  file_size;
char *file_conts;

fd = fopen( "/tmp/myfile", "rb" );
if (fd==NULL){ fputs("File does not exists", stderr); exit(1); }


// get filesize
//

fseek( fd, 0, SEEK_END );
file_size = ftell(fd)
rewind(fd);



// allocate memory to store file (in HEAP)
//

file_conts = (char*) malloc( file_size );
if (file_conts == NULL) {fputs("Memory Error",stderr); exit(2)};



// write file to file_conts
//

result = fread( file_conts, 1, file_size, fd );
if (result != file_size) {fputs("Reading Error",stderr); exit(3)};


fclose(fd);
free(file_conts);	// we allocated memory for file, must free it now

fgetline

There is no fgetline in C. use C++.