使用C中的格式说明符从fprinft中的char缓冲区读取索引的特定范围

问题描述 投票:1回答:1

我将尝试通过到目前为止的问题和解决方案来详细描述。我当前拥有的解决方案不是最佳解决方案,我想使其更好。

注意:char inputline[1024]没有特定格式,它可以具有任何格式的字符串。 char inputline [1024]从具有数千行的文件中逐行读取行。这就是为什么优化对我来说非常重要的原因。

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

问题是我正在阅读"%c",但这不是很理想,我想改用%s。但是我无法理解如何在写入文件时通过在格式说明符中指定fprintf(outfile, "%c", inputline[prev_index + i]);来将"%s"转换为使用prev_index + i,因为我只想基于循环到inputline[prev_index + i]中的字符写入文件。

c
1个回答
1
投票

您可以使用格式说明符%.*s并传递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;
}

输出:

他是

或者,您可以使用strncpy()来创建子字符串并使用它:

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;
}

注意,您必须在代码中输入#include <string.h>

输出:

他是

© www.soinside.com 2019 - 2024. All rights reserved.