2016-12-07 66 views
0

所以我想编写一个程序,需要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; 
} 

谢谢!

+0

什么是你的问题? – kaylum

+0

请指出预期的输出示例。 – BLUEPIXY

+0

不会argv从argv [0]开始而不是argv [1]? –

回答

1

问题是如何fgets工作。它旨在读取下一行的末尾,最大数量为size个字符,以先到者为准。如果读一个换行符之前读取size字符,它返回size - 长度字符串,但它留下的行的其余部分在输入流中,准备在下次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; 
} 
+0

我明白你说的是什么,但是这不是说strncpy行会做什么?基本上复制整行读入,到一个新行,然后写入写入文件? –

+0

假设你正在读取一行10000个字符的文件,其中'size'设置为10.下面是你的循环对'strncpy'版本的处理:(1)使用'fgets',读下一个9从'f1'到'content'缓冲区中的字符和NUL终止总共10个字符; (2)使用'strncpy',将这9个字符加NUL终止符从'content'复制到'line'; (3)将这9个字符打印到'f2';和(4)循环回到开始以获得接下来的9个字符。 –

+0

嗯,好吧,我明白了。如果没有问题,你介意发布一个工作解决方案吗? –

相关问题