tags:

views:

49

answers:

2

I have a server side C based CGI code as:

cgiFormFileSize("UPDATEFILE", &size);   //UPDATEFILE = file being uploaded
cgiFormFileName("UPDATEFILE", file_name, 1024);
cgiFormFileContentType("UPDATEFILE", mime_type, 1024);
buffer = malloc(sizeof(char) * size);

if (cgiFormFileOpen("UPDATEFILE", &file) != cgiFormSuccess) {
    exit(1);
}
output = fopen("/tmp/cgi.tar.gz", "w+");

inc = size/(1024*100);
fptr = fopen("progress_bar.txt", "w+");    
while (cgiFormFileRead(file, b, sizeof(b), &got_count) == cgiFormSuccess)
{
    fwrite(b,sizeof(char),got_count,output);
    i++;
    if(i == inc && j<=100)
    {
     fprintf(fptr,"%d", j);
     fflush(fptr);
     i = 0;
     j++;   // j is the progress bar increment value
    }
}
fclose(fptr);
cgiFormFileClose(file);
retval = system("mkdir /tmp/update-tmp;\
                 cd /tmp/update-tmp;\
                 tar -xzf ../cgi.tar.gz;\
                 bash -c /tmp/update-tmp/update.sh");

However, this doesn't work the way as is seen above. Instead of printing 1,2,...100 to progress_bar.txt (referred by fptr)one by one it prints at ONE GO, seems it buffers and then writes to the file. fflush() also didn't work.

Any clue/suggestion would be really appreciated.

A: 

First, open the file before the loop and close after it ends. Too much IO.

The problem is here w+ - this truncates your file. use a+. (fopen help)

Am
I tried that as well. Open the file before loop and close it after the loop, it doesn't work either. I do not want to append data, I want to update data every time that's why I used w+
Punit
then why do u use fseek?
Am
To print the value at the start of file every time, however in this case this is not necessary as file open and close are done everytime.
Punit
ok, so u expected the end result to be that file containing "99"?
Am
A: 

It is writing it one-by-one, it's just that it does it so fast that you're vanishingly unlikely to ever see the file with a value other than 99 in it.

This is easily demonstrated if you put a sleep(1) within the loop, so that it's slow enough for you to catch it.

caf
It does so (i tried sleep(1);), however not at the point desired. Once CGI has done copying data,and writing to the text file; after that it prints to text file.
Punit
What makes you think that `cgiFormFileRead()` is called slowly, as the file uploads? It appears far more likely that the uploaded file is buffered completely and then provided to your CGI.
caf
You are right, something this kind is happening. However, I didn't understand "cgiFormFileRead() is called slowly, as the file uploads" Do you have any idea what should I try now
Punit