First there are few problems with your code. Before addressing those, here are a few other things I would do. First, define a type for the strings you are using. :
const int StrSize = 49;
typedef char textStr[ StrSize + 1 ];
The +1 is used so you don't have to subtract 1 to get the size of the buffer minus a spot the null character. Second, I would use primarily local variables declared within the function. You will see this in the code.
About that code, it doesn't make sense to me why you update three variables from three widgets and then overwrite those values with data from the file. Also, why is
i
looping 5 times and doing the same thing with the same data each time? That also doesn't make sense.
Before I get into the revised code I want to make one small point about outputting data. I always try to leave the cursor at the front of a line (position 0) when ever possible. That makes it easier because you always know where it is when you start and you can reset it every time by placing the newline character at the end of the line. The revisions will do this.
So here is revised code with the for loop on
i
omitted :
#define VFMT " %29[^ , ]";
void newForm::Update(){
FILE * fptr = fopen("/root/Desktop/simple.txt", "r+");
if (fptr == NULL)
{
printf("Could not open file");
return;
}
textStr str, name, class, grade, var1, var2;
char buf[100] = { 0 };
while(fgets( buf, sizeof( buf ) - 1, fptr ) != NULL){
int n;
if(3 == sscanf(buf, VFMT " " VFMT " " VFMT "%s", name"%n", class"%n", grade"%n", &n ) && buf[n] =='\0'){
const char * text = nullptr;
if( stricmp( var2,"Name") == 0) text = name;
else if( stricmp( var2,"Class") == 0)
text = class;
else if( stricmp( var2,"Grade") == 0)
text = grade;
else
{
fprintf( stderr, "error - unrecognized item : '%s'\n", var2 );
break;
}
fprintf( fptr," %s\n", text ); } else
break;
}
fclose( fptr );
}
This doesn't do exactly what you want because I can't make sense of what's going here. To use fprintf to generate a fixed-width output , 3 wide, you can do this :
fprintf( fptr, "%3s", stringValue ); fprintf( fptr, "%-3s", stringValue );
Best of luck with it.