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.
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;
}
Comments