繁体   English   中英

如何将每行中特定数量的字符从一个文件复制到另一个文件

[英]How to copy specific number of characters from each line from one file to another

因此,我正在尝试编写一个包含3个命令行参数的程序,即1.现有文件的名称,2。新文件的名称,3。从每一行复制到新文件的字符数。

这是我到目前为止的内容:

int main(int argc, char *argv[]) {

    int size = atoi(argv[3]); // The number of characters to copy 
    char content[size];
    char line[size];

    FILE *f1 = fopen(argv[1], "r"); // Read from first file                                                          
    FILE *f2 = fopen(argv[2], "w"); // Write to second file                                                          

    if (f1 == NULL || f2 == NULL) {
        printf("\nThere was an error reading the file.\n");
        exit(1);
    }

    while (fgets(content, size, f1) != NULL) {
        // This is what I had first:
        fprintf(f2, "%s", content);                                                                                 

        // And when that didn't work, I tried this:
        strncpy(line, content, size);
        fprintf(f2, "%s", line);                                                                                           
    }

    fclose(f1);
    fclose(f2);
    return 0;
}

提前致谢!

问题是fgets如何工作。 它旨在读取下一行的末尾最大size字符,以先到者为准。 如果它在读取换行符之前先读取了size字符,则返回该size -length字符串,但将其余行留在输入流中,准备由下一个fgets调用读取! 因此,如果size为10,则循环仅读取10个字符块中的长行,但仍然输出完整行,一次输出10个字符。

如果要保留当前程序的结构,诀窍将是使用fgets读取整行(使用比最长的最长行更长的缓冲区和size值),如果存在,请删除换行符,然后截断将行换成n字符(例如,通过NUL终止),然后打印出缩短的行。

这足够一个提示,还是您只想要一个可行的示例?

编辑:好的,这是一个可行的解决方案。

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

char line[4096];

int main(int argc, char *argv[]) {

    int size = atoi(argv[3]); // The number of characters to copy

    FILE *f1 = fopen(argv[1], "r"); // Read from first file
    FILE *f2 = fopen(argv[2], "w"); // Write to second file

    if (f1 == NULL || f2 == NULL) {
        printf("\nThere was an error reading the file.\n");
        exit(1);
    }

    // read whole line
    // note: if the whole line doesn't fit in 4096 bytes,
    // we'll be treating it as multiple 4096-byte lines
    while (fgets(line, sizeof(line), f1) != NULL) {

        // NUL-terminate at "size" bytes
        // (no effect if already less than that)
        line[size] = '\0';

        // write up to newline or NUL terminator
        for (char* p = line; *p && *p != '\n'; ++p) {
            putc(*p, f2);
        }
        putc('\n', f2);

    }

    fclose(f1);
    fclose(f2);
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM