2

我试图用来strcmp()测试文本文件中的特定行是否等于换行符(\n)。我从一个文本文件中收集每一行,并将它们写入另一个文本文件。如果源文件中的整行只是一个换行符,我不想在目标文件中写入该行。

我认为下面的代码可以用于此目的,但事实并非如此。但是,如果我将条件中的数值从 0 更改为 3,它就像我希望它工作一样工作。知道为什么吗?

我的目标是更改我的条件,使其使用数值 0,这意味着strcmp()找到完全匹配,但我不知道如何更改我的条件的其他部分来做到这一点。

#include <stdio.h>

void process_file(const char *inp_file, FILE *otp_fp) {

  char line[256];
  FILE *inp_fp = fopen(inp_file, "r");

  if (inp_fp != NULL) {
    while(fgets(line, 256, inp_fp) != NULL) {

      if (strcmp (line, "\n") != 0) { //changing to 3 gets desired result
        fprintf(otp_fp, line);
      }

    }
  }

  fclose(inp_fp);

}
4

2 回答 2

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

void process_file(const char *inp_file, FILE *otp_fp) {

  char line[256];
  FILE *inp_fp ;
  size_t len;

  inp_fp = fopen(inp_file, "r");

  if (!inp_fp ) return;

  while(fgets(line, 256, inp_fp) != NULL) {
    len = strlen(line);
        /* skip trailing space */
    while (len && (line[len-1] == '\n' || line[len-1] == '\r')) {line[--len] = 0;}

    if (!len ) continue;
        /* dont use random strings as format argument for printf() et.al.
        ** (there could be '%' signs in it) 
        ** Note: the \r\n (if any) were removed, and now are re-added.
        ** This will impose the line-ending convention that the current platform uses.
        */
    fprintf(otp_fp, "%s\n", line);

  }

  fclose(inp_fp);

}
于 2012-10-28T11:33:15.850 回答
1

您描述的行为的唯一解释是这些行并不是真的空的。它们必须有一些空格(如空格或制表符)。如果你想省略这些行,那么你必须检查它们是否真的只包含空格。

(我还修复了代码中的一个问题,如果失败,您将尝试fclose()使用 NULL 指针fopen()。这也演示了如何通过仅在处理错误条件后运行代码来降低函数的缩进级别。)

int str_is_whitespace(const char* line) {
    int onlyws = 1;
    int i = 0;
    while (onlyws && line[i] != '\0') {
        if (!isspace(line[i])) {
            onlyws = 0;
        }
        ++i;
    }
    return onlyws;
}

void process_file(const char *inp_file, FILE *otp_fp) {
    char line[256];
    FILE *inp_fp = fopen(inp_file, "r");
    if (inp_fp == NULL) {
        return;
    }
    while(fgets(line, 256, inp_fp) != NULL) {
        // Only output the text if it doesn't consist only of whitespace.
        if (!str_is_whitespace(line)) {
            fprintf(otp_fp, "%s", line);
        }
    }
    fclose(inp_fp);
}

您需要包含<ctype.h>for isspace()

请注意,您会遇到长度超过 255 个字符的行的问题,并且fgets()碰巧读取了其中只有空格的行的剩余部分。如果你想处理这个问题,你需要额外的逻辑来确定当前文本是否实际上是更大行的一部分。

于 2012-10-28T09:01:45.867 回答