【问题标题】:Copying Only Part of a File to a New One in C仅将文件的一部分复制到 C 中的新文件
【发布时间】:2017-11-21 17:30:59
【问题描述】:

我有一个 C 练习题,要求我创建一个函数,该函数只将文​​件的一部分复制到另一个文件。限制是大于 maxlen 个字符的行不复制到新文件中,换行符不计算在内,所以不应该复制。我的部分函数说,如果文件不存在,它应该明确说明,当我运行该代码时,我会收到这些错误消息;但是,我可以看到创建的文件在我的文件夹中。每当我在运行代码后打开我试图读取的文件时,我都会得到这个:

./Debug/main.c.o ./Debug/dot.c.o ./Debug/dataBase.c.o ./Debug/intPrompt.c.o ./Debug/numWords.c.o ./Debug/LinkedList.c.o   

下面是我的代码:

void shortLines(char* f1, char* f2, int maxlen) {
    FILE* fp = fopen(f1, "r");
    FILE* fp2 = fopen(f2, "w");
    if (fp == NULL) {
        perror("File does not exist");
    }
    if (fp2 == NULL) {
        perror("File does not exist");
    }
    char singleLine[maxlen];
    char check;
    size_t len;
    do {
        fgets(singleLine, maxlen, fp);
        len = strlen(singleLine);
        if (singleLine[len-1] == '\n') {
            singleLine[len-1] = '\0';
        }
        fprintf(fp2, "%s", singleLine);
    } while ((check=getc(fp) != EOF));
}

int main(int argc, char **argv) {
    shortLines("Andrew.txt", "Andrew2.txt", 25);
    return 0;
}

【问题讨论】:

  • 如果您使用的是 POSIX(或其他带有getline 的系统),最好使用getline,例如here。顺便说一句,您最好将calloc 用于char*singleLine;
  • 为什么当文件不存在时打印出错误消息,然后继续尝试读取/写入它们?
  • @Chris Turner 文件确实存在,这就是为什么我很困惑我收到错误消息。
  • 它们可能存在,但无论出于何种原因,您的代码都无法打开它们,因此当 fpNULL 时继续操作是徒劳的。
  • 你应该写perror(f1)而不是perror("file does not exist")。完全有可能问题不是不存在,并且“文件不存在:权限被拒绝”形式的错误消息只是令人困惑。

标签: c file loops pointers file-io


【解决方案1】:

我刚刚创建了名为 Andrew.txt 和 Andrew2.txt 的新文件,这些文件似乎出于某种奇怪的原因工作。无论如何,代码中存在一些问题。首先,在调用 fgets 之后,我需要确保清除该行中剩余的字符。我用一个while循环和fgetc来做到这一点。如果我到达一个 EOF,那么我继续,然后 fgets 也返回一个 EOF,从而打破了外循环。

void shortLines(char* f1, char* f2, int maxlen) {
    FILE* fp = fopen(f1, "r");
    FILE* fp2 = fopen(f2, "w");
    if (fp == NULL) {
        perror(f1);
    }
    if (fp2 == NULL) {
        perror(f2);
    }
    char line[maxlen+1];
    size_t len;
    char c;
    while (fgets(line, maxlen+1, fp) != NULL) {
        len = strlen(line);
        if (len == maxlen) {
            while ((c=fgetc(fp)) != '\n') {
                if (feof(fp)) {
                    break;
                }
            }
            continue;
        }
        if (line[len-1] == '\n') {
            line[len-1] = '\0';
        }
        fprintf(fp2, "%s\n", line);
    }
}

【讨论】:

    猜你喜欢
    • 2016-06-11
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 2013-12-09
    • 2018-06-29
    • 2016-04-30
    相关资源
    最近更新 更多