My Tech notes: C Program Usage fseek fopen ftell and fprintf
Subscribe

Unix Documentation

Free Online Unix Training Materials

Lists many links to free Unix training materials.

Pointers and Arrays Materials

Pointers and Arrays materials Explained for C beginners

C FAQ and General Questions C Interview Questions

Powered By

Free XML Skins for Blogger

Powered by Blogger

Thursday, September 25, 2008

C Program Usage fseek fopen ftell and fprintf

I need a c program to write update values in a file. Here is simple logic for it.
steps.
open file.
set the file pointer using fseek. (same as lseek)
write the value.
close the file.
int fseek(FILE *stream, long offset, int whence);

off_t lseek(int fildes, off_t offset, int whence);
The lseek function repositions the offset of the file descriptor fildes to the argument
offset according to the directive whence as follows:

SEEK_SET
The offset is set to offset bytes.

SEEK_CUR
The offset is set to its current location plus offset bytes.

SEEK_END
The offset is set to the size of the file plus offset bytes.

Some more notes on this;
From step one one can open file in read mode or r+ mode; then in second step set the file pointer to the end of file using fseek, with SEEK_END.
using fprintf update the values in file.

The other way to do this is open file in append mode, then no need to setting file pointer, as if file is opened in append mode; the file pointer will be set at end of file;

here is c code snippet.

#include

int main()
{
FILE *fptr;
int pos;
fptr = fopen("root","a");

if(fptr != NULL)
{
fprintf(fptr,"%s\n","test");
pos= ftell(fptr);

printf("pos %d\n",pos);
}
else
printf("can't open file\n");
fclose(fptr);
return 0;
}

No comments:

Post a Comment