简体   繁体   English

如何在C中逐字将内容从一个文件复制到另一个文件?

[英]How to copy contents from one file to another word by word in C?

I know how to copy contents from one file to another character by character, but I am supposed to do it word by word. 我知道如何将一个文件中的内容逐个字符地复制到另一个文件中,但是我应该逐字地进行复制。 I tried this code, but when I run this, my output file ends up having each word on a new line. 我尝试了这段代码,但是当我运行此代码时,我的输出文件最终将每个单词放在换行符上。 How am I supposed to copy contents from one file to another (as is) word by word? 我应该如何逐个单词地将内容从一个文件复制到另一个文件?

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

int main(int argc, char* argv[])
{
    // Error checking
    if(argc < 3)
    {
        fprintf(stderr, "Please print two arguments");
        exit(EXIT_FAILURE);
    }

    char* input = argv[1];
    char* output = argv[2];
    char buffer[4096];

    FILE* fp_open = fopen(input, "r");
    if(fp_open == NULL) fprintf(stderr, "Unable to open input file");

    FILE* fp_write = fopen(output, "w");
    if(fp_write == NULL) fprintf(stderr, "Unable to open output file");

    while(fscanf(fp_open, "%s", buffer) == 1)
    {
        fprintf(fp_write,"%s\n", buffer);
    }

    fclose(fp_open);
    fclose(fp_write);

    return 0;
}

Note: I am only allowed to use fscanf("%s") for reading from an input file. 注意:只允许使用fscanf("%s")从输入文件中读取。

PS I also know that it is inefficient way to do it, but this is what I am supposed to do. PS我也知道这是一种低效的方法,但这是我应该做的。

since the request is to read the string using fscanf only, use the following logic : 由于请求仅使用fscanf读取字符串,因此请使用以下逻辑:

char c;
char tmpbuffer[100], buffer[1000];

fp = fopen("file.txt","r");
while(fscanf(fp,"%s",tmpbuffer)!=-1)
{
strcat(buffer,tmpbuffer,strlen(tmpbuffer));
while((c = fgetc(fp)) == " ")
{
strcat(buffer,&c,1);
}
fseek(fp,-1,SEEK_CUR);
}

here the buffer contains the entire string in a line so you can write the entire line into the output file. 此处缓冲区包含一行中的整个字符串,因此您可以将整行写入输出文件。

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

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