c

read specific range of index from char buffer in fprinft using format specifiers in C


I will try to describe by problem and solution that I have as of now in detail. The solution I currently have is not optimal and I want to make it better.

Note: char inputline[1024] has no specific format, it can have strings of any format. The char inputline[1024] reads lines one by one from a file with thousands of lines. So that is why optimization is very important for me.

FILE *outfile = fopen("tests.txt", "w");
int start_index = 1; //index from where I want to write the characters from the inputline array to the file
int prev_index = start_index; //keep track of last character position written to file

char inputline[1024] = {"12044 This is the test String 2019 to 2025 is another test& and 2050"};
int loop_count = 6; // This can vary as I have just hardcoded a value here for testing
int i;        
for(i=0; i<loop_count; ++i)
{
    fprintf(outfile, "%c", inputline[prev_index + i]);
}
prev_index = prev_index + loop_count;// this keeps track of last position of character written to file at end
Sample input in char inputline[1024] = {"This is my day in 2020 1230023"}

Desired output in tests.txt: (for loop will loop 6 times as loop_count is 6)
his is

The issue is that I am reading "%c" and this is not very optimal and I want to use %s instead. But I am not able to understand how can I convert the fprintf(outfile, "%c", inputline[prev_index + i]); to use "%s" by specifying the prev_index + i in format specifier when writing to file as I only want to have the characters from inputline[prev_index + i] based on the loop to be written to the file.


Solution

  • You can use the format specifier %.*s and pass in a length

    https://ideone.com/UdC3aH

    #include <stdio.h>
    
    int main(void) {
        int start_index = 1;
        int length = 6;
        char inputline[] = "This is my day in 2020 1230023";
    
        printf("%.*s\n", length, inputline + start_index); //  you can use fprintf(outfile, "%.*s", length, inputline + start_index); here
        return 0;
    }
    

    Output:

    his is

    Alternatively you could use strncpy() to make a substring and use that:

    https://ideone.com/oyRJuG

    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
        int start_index = 1;
        int loop_count = 6;
        char inputline[] = "This is my day in 2020 1230023";
        char substr[1024];
    
        strncpy ( substr, inputline + start_index, loop_count);
        substr[loop_count] = '\0';
        printf("%s\n", substr); //  you can use fprintf(outfile, "%s", substr); here
        return 0;
    }
    

    Note that you have to #include <string.h> in your code

    Output:

    his is