Tuesday, April 2, 2013

How to write LoadRunner/VuGen Output to external file

Compatibility: This script will work in all version of LoadRunner/VuGen
Following C lanuage function in LoadRunner will be used in this articles:
  • long fopen( const char *filename, const char *access_mode ); //To open file
  • int fprintf( FILE *file_pointer, const char *format_string [, args ] ); //To write formatted output
Step 1: Define the file name to be used or created or to be added. Make sure to replace one backslash with two backslashes. Set access mode and file stream.
//Name and location of a file to be open or created.      
char * filename = "c:\\temp\\logfile.txt";     
/*** access mode ***;      
* r or r+ = open for reading      
* w or w+ = open for writing      
* a or a+ = open for appending      
* t = text mode      
* b = binary mode      
* where the "+" sign indicates that the file must already exist  *******************/      
// Open the file with append mode      
char * access_mode = "a+";  
//File pointer  long file_stream;
Step 2: Open the file with an access mode. If it can't open LoadRunner error function will display error.
if ((file_stream = fopen(filename, access_mode)) == NULL)  { 
lr_error_message ("Cannot open or create %s", filename);   
return -1;
}
Step 3: Write message to output file
fprintf(file_stream, "This is the message to output file");
Step 4: fclose(file_stream); Complete Source Code:
//Name and location of a file to be open or created.     
char * filename = "c:\\temp\\logfile.txt";     
/*** access mode ***      
* r or r+ = open for reading      
* w or w+ = open for writing      
* a or a+ = open for appending      
* t = text mode      
* b = binary mode      
* where the "+" sign indicates that the file must already exist      *******************/     
// Open the file with append mode     
char * access_mode = "a+";     
//File pointer     
long file_stream;          
if ((file_stream = fopen(filename, access_mode)) == NULL) {         
lr_error_message ("Cannot open or create %s", filename);         
return -1;     
}     
//Write message to output file     
fprintf(file_stream, "This is the message to output file");          
//Close the file stream     
fclose(file_stream);



3 comments:

Rick Carter said...
This comment has been removed by the author.
Rick Carter said...

Hi! Very useful!

If I had multiple VUsers writing to the same file, are there any concurrency issues or will the filesystem properly sort it out? Also, if in that case I had the same VUser writing to the file at widely-separated places (think a capture of some values at the start and a confirmation at end of each time through), would it be better for me to fopen and fclose surrounding each of the writes, or should I just fopen before first and fclose after second? Finally, should the VUser fail, will there be memory issues or will it clean up after itself?

Goodtech Consulting said...

Thanks for sharing it. Performance Testing Services