Skip to content

Instantly share code, notes, and snippets.

@benaryorg
Last active August 29, 2015 14:19
Show Gist options
  • Save benaryorg/d9411c2405834d1b1b2f to your computer and use it in GitHub Desktop.
Save benaryorg/d9411c2405834d1b1b2f to your computer and use it in GitHub Desktop.
read/write file in C
#include <stdio.h>
#define USED_FILE "file.txt"
void write(void)
{
FILE *f=fopen(USED_FILE,"rb");
//I always use 'b' for binary because it does not make any difference except the thing with EOF.…
//in text mode -1==EOF, that means if a file contains the byte 0xff this is interpreted as EOF even if the file is longer
if(f)
{
//file already exists
//(maybe convert this to a while loop and try to ask the user for another file here and set f accordingly)
return;
}
f=fopen(USED_FILE,"wb");//there is also 'a' which means append
//now write with either fprintf, fwrite, fputs, fputc
//link: http://en.cppreference.com/w/c/io/<function name>
int i;
for(i=0;i<=10;i++)
{
fprintf(f,"i=%2d;%s;i^2=%3d\n",i,(i%2)?"odd":"even",i*i);
}
}
void read(void)
{
FILE *f=fopen(USED_FILE,"rb");
if(!f)
{
//does not exist
return;
}
while(!feof(f))
{
putchar(fgetc(f));
}
//now write with either fscanf (DO NOT USE), fread, fgets, fgetc
//link: http://en.cppreference.com/w/c/io/<function name>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment