C 使用 fprintf 字符串 %.*s

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv) {
/*  return 0;  */
FILE *in, *out;
char text_buffer[80];
char text_buffer2[80];
puts ("This program converts file from 16 columns to 8 cols with second half of file on next line");
    printf ("Input File:");
    gets (text_buffer);
    sscanf (text_buffer, "%79s", text_buffer2);
    if ((in = fopen (text_buffer2, "rt")) == NULL)
    {
        puts ("Can't open input file!");
        exit (EXIT_SUCCESS);
    }
        puts (text_buffer2);
    printf ("Output File:");
    gets (text_buffer);
    sscanf (text_buffer, "%79s", text_buffer2);
    if ((out = fopen (text_buffer2, "wt")) == NULL)
    {
        puts ("Can't open output file!");
        exit (EXIT_SUCCESS);
    }
    printf ("Working...");
        puts ("A");
        puts (text_buffer2);
    char buffer[17];
    while (fgets(buffer, sizeof(buffer), in) != NULL) {
        // Copy first 32 characters to the output file
        fprintf(out, "%.*s\n", 8, buffer);

        // Copy characters 32 to 64 to the second line in the output file
        fprintf(out, "%.*s\n", 8, buffer + 8);
    }  
// Close input and output file in and out 
fclose(in);
fclose(out);
printf("Conversion completed successfully.\n");
return 0;
}

我的输入文件是

    123456789ABCDEF0
    AAABBBCCCDDDEEFF
    123456789ABCDEF0

输出文件应该是

    12345678
    9ABCDEF0
    AAABBBCC
    CDDDEEFF
    12345678
    9ABCDEF0

但是我得到的输出有 3 行和 4 行空白,5 行重复第 2 行。 剩下的 有人能找到错误吗?

它必须在 8, buffer + 8) 线上? 我使用 strncpy 更改了 while 循环,并且有效。

c string printf
1个回答
0
投票

下面通过替换 while 循环进行的修改是有效的,但我需要知道上面的代码有什么问题

/* this while works correctly
while (fgets(line, sizeof(line), in) != NULL) {
    int lineLength = strlen(line);
    int halfLength = lineLength / 2;

// Split line into first half and second half
    char firstHalf[halfLength + 1];
    char secondHalf[halfLength + 1];

    strncpy(firstHalf, line, halfLength);
    firstHalf[halfLength] = '\0';
    strncpy(secondHalf, line + halfLength, halfLength);
    secondHalf[halfLength] = '\0';
// Write the desired output to file out
    fprintf(out, "%s\n%s\n", firstHalf, secondHalf);
}
*/
© www.soinside.com 2019 - 2024. All rights reserved.