Originally posted by DaveHope
Essentially, how do I write to a file in C?
What Machewy gave is C++.
Code:
#include<stdio.h>
int main()
{
int i,j; /*int's are four bytes long*/
FILE *file;
char *tmpfname;
printf("Enter integer: ");
scanf("%d",&i);
tmpnam(tmpfname); /*create a temporary file name*/
file=fopen(tmpfname,"wb+"); /*create a file for binary read/write*/
free(tmpfname);
fwrite(&i,4,1,file); /*write one four byte object to file from the buffer &i*/
fseek(file,0,SEEK_SET); /*set the file position 0 bytes from the beginning of the file*/
fread(&j,4,1,file); /*read one four byte object from file to the buffer &j*/
printf("Read integer: %d\n",j);
fclose(file);
return 0;
}
You do not have to know the file size. You have to know either the structure of the file and/or the file must contain data on the structure of the file. In my example, I knew everything about the structure of the file. In an image file, the file must have width, height and bits per pixel information so I can figure out how much pixel data to read.