一次从文件中读取2行,然后在C中交替将两行合并为一行

时间:2019-03-20 18:00:10

标签: c

如何一次从文件中读取两行,然后使用指针将两行交替地合并为C中的一行。

样本输入:

ABCDE
PQRSTFG
acegikmoqsuwyz
bdfhjlnprtvx

输出:

APBQCRDSETFG
abcdefghijklmnopqrstuvwxyz

1 个答案:

答案 0 :(得分:1)

提案:

stdin.println("\""+tesseract_install_path+"\" \""+file+"\" \""+output_file+"\" -l eng");

编译和执行:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char * readLine(ssize_t * ln)
{
  char * lineptr = NULL;
  size_t n = 0;

  *ln = getline(&lineptr, &n, stdin);

  if (*ln <= 0) {
    if (lineptr != NULL)
      free(lineptr);
    return NULL;
  }

  if (lineptr[*ln - 1] == '\n')
    lineptr[--*ln] = 0;

  return lineptr;
}

int main()
{
  size_t sz = 0;
  char ** lines = NULL;

  for (;;) {
    ssize_t n1;
    char * l1 = readLine(&n1);

    if (l1 == NULL)
      break;

    ssize_t n2;
    char * l2 = readLine(&n2);
    char * l;

    if (l2 == NULL) {
      /* consider the second line is empty if missing */
      l = l1;
    }
    else {
      l = malloc(n1 + n2 + 1);

      if (l == NULL) {
        fprintf(stderr, "not enough memory\n");
        return -1;
      }

      char * p1 = l1;
      char * p2 = l2;
      char * p = l;

      for (;;) {
        if (! *p1) {
          strcpy(p, p2);
          break;
        }
        *p++ = *p1++;
        if (! *p2) {
          strcpy(p, p1);
          break;
        }
        *p++ = *p2++;
      }
      free(l1);
      free(l2);
    }

    /* realloc for more than just 1 additional entry if lot of lines to manage */
    lines = realloc(lines, ++sz * sizeof(char *));
    if (lines == NULL) {
      fprintf(stderr, "not enough memory\n");
      return -1;
    }
    lines[sz - 1] = l;
  }

  /* debug and free */
  for (size_t i = 0; i != sz; ++i) {
    puts(lines[i]);
    free(lines[i]);
  }

  free(lines);
}

valgrind 下执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra l.c
pi@raspberrypi:/tmp $ cat f
ABCDEP
QRSTFG
acegikmoqsuwyz
bdfhjlnprtvx
pi@raspberrypi:/tmp $ ./a.out < f
AQBRCSDTEFPG
abcdefghijklmnopqrstuvwxyz