Saturday, March 18, 2023

How to read contents of a text file through LoadRunner and make alterations to that text file | Read text file with load runner

To read the contents of a text file t in LoadRunner, we have to use fopen, fread, fwrite, and fclose. Here's my sample code.

Action()
{
    char buffer[1024];
    FILE *fp = fopen("example.txt", "r+"); // Replace "example.txt" with the path to your text file

    if (fp != NULL)
    {
        // Read the contents of the file into a buffer
        size_t num_read = fread(buffer, 1, sizeof(buffer), fp);

        if (num_read > 0)
        {
            // Make alterations to the buffer as needed
            // For example, replace all occurrences of "foo" with "bar":
            char *ptr = buffer;
            while ((ptr = strstr(ptr, "foo")) != NULL)
            {
                memcpy(ptr, "bar", 3);
                ptr += 3;
            }

            // Write the modified buffer back to the file
            fseek(fp, 0, SEEK_SET);
            fwrite(buffer, 1, num_read, fp);
            fflush(fp);
        }

        fclose(fp);
    }
    else
    {
        lr_error_message("Failed to open file for reading and writing.");
    }

    return 0;
}

Here we first use fopen to open the file named "example.txt" for both reading and writing, and store the resulting file pointer in the fp variable. If the file is successfully opened, we then use fread to read the contents of the file into a buffer named buffer, up to a maximum of 1024 bytes. Next, we make alterations to the buffer as needed. In this example, we use strstr to search for all occurrences of the string "foo" within the buffer, and replace them with the string "bar". You can modify this logic to suit your specific use case.

Finally, we use fseek to set the file position indicator back to the beginning of the file, fwrite to write the modified buffer back to the file, and fflush to flush any remaining output to the file. We then close the file using fclose.

No comments: