Hello

I am trying to write data to a file.

When writing "STEPHEN", only STEP is written, can anyone help?

below is my code

fp = fopen(filename, "rb+" );

fseek(fp, final_seek_pos, SEEK_SET );
fwrite(update_record, sizeof(update_record),1 ,fp );

fclose(fp);

how is update_record defined? It would appear to be a structure, not a simple string as you illustrated. We need more information to help you.

What is final_seek_pos???

#include <stdio.h>
void main()
{
FILE *fp;
char update_record[40] = "STEPHEN";
fp = fopen("test.txt", "rb+" );
fseek(fp, 0, SEEK_SET );
fwrite(update_record, sizeof(update_record),1 ,fp );
fclose(fp);
}

This code is printing STEPHEN for me.

final_seek_pos is whatever position i am writing to in the file and is an int.

The flat file looks something like this

MR GRAHAM GRIFFITHS

I want to write at position set position to be 10 ( start of GRAHAM ), and overwrite with STEPHEN, but only overwriting first 4 characters

/************************************************************************
* Function     : write_records
* Description  : write updated records to file
***********************************************************************/
void write_records(int row, int screen_pos, char *update_record, const int InLRecL, const int field, const int SchemaFlag, const char *filename, const char *schema, const unsigned int DisplayHexFlag, unsigned long long total_bytes )
{
FILE *fp;
long working_seek_pos;
long final_seek_pos;
int   len=0;


row=row-3;
if ( RECORD_NUM >= 16 )
{
RECORD_NUM=RECORD_NUM-16;
working_seek_pos=RECORD_NUM+row;
working_seek_pos=working_seek_pos*InLRecL;
}
else
{
RECORD_NUM=RECORD_NUM-3;
working_seek_pos=InLRecL*row;
}


final_seek_pos=working_seek_pos+screen_pos-1;
len = strlen(update_record);


if ( len < InSchStruct[field].field_length )
{


do {


strcat(update_record, " " );
len++;
}while( len != InSchStruct[field].field_length );
}


/* Write records */
fp = fopen(filename, "rb+" );
fseek(fp, final_seek_pos, SEEK_SET );
fwrite(update_record, sizeof(update_record),1 ,fp );


fclose(fp);


}

Edited 3 Years Ago by happygeek: fixed formatting

I have one suggestion. Instead of giving sizeof(update_record),
in fwrite, directly give 40 and try. I think that is creating the problem.
The sizeof pointer will be 4 bytes so the first four bytes are getting printed. The best thing u can do is pass the sizeof string also as one arg and use it in fwrite.
It should work.

I have one suggestion. Instead of giving sizeof(update_record),
in fwrite, directly give 40 and try. I think that is creating the problem.
The sizeof pointer will be 4 bytes so the first four bytes are getting printed. The best thing u can do is pass the sizeof string also as one arg and use it in fwrite.
It should work.

Works!!!


Thank you very much

This article has been dead for over six months. Start a new discussion instead.