Reading the full content of a text file using dynamic memory allocation (malloc) - Loadrunner

Loadrunner
Overview:

When we are trying to perform uploading files of different size scenario in loadrunner the below C Program comes handy.

C Program:

#define SEEK_SET 0 /* beginning of file. */
#define SEEK_CUR 1 /* current position. */
#define SEEK_END 2   /* end of file */


Action()
{
 long infile; // file pointer
 char *buffer; // buffer to read file contents into
 char *filename = "test.txt"; // file to read
 int fileLen; // file size
 int bytesRead; // bytes read from file
 //
 // open the file
 infile = fopen(filename, "rb");
 if (!infile) {
    lr_error_message("Unable to open file %s", filename);
    return;
 }


 // get the file length
 fseek(infile, 0, SEEK_END);
 fileLen=ftell(infile);
 fseek(infile, 0, SEEK_SET);
 lr_log_message("File length is: %9d bytes.", fileLen);


 // Allocate memory for buffer to read file
 buffer=(char *)malloc(fileLen+1);
 if (!buffer) {
    lr_error_message("Could not malloc %10d bytes", fileLen+1);
    fclose(infile);
    return;
 }


 // Read file contents into buffer
 bytesRead = fread(buffer, 1, fileLen, infile);
 if (bytesRead != fileLen)
 {
    lr_error_message("File length is %10d bytes but only read %10d bytes", fileLen, bytesRead);
 }
 else
 {
    lr_log_message("Successfully read %9d bytes from file: ", bytesRead);
 }
 fclose(infile);


 // Save the buffer to a loadrunner parameter
 lr_save_var( buffer, bytesRead, 0, "fileDataParameter");
 free(buffer);
 lr_log_message("File contents: %s", lr_eval_string("{fileDataParameter}"));
}

No comments:

Post a Comment