![](/img/trans.png)
[英]If a certain word exists in the .txt file, copy that word to another txt file
[英]How to copy contents from one file to another word by word in C?
我知道如何將一個文件中的內容逐個字符地復制到另一個文件中,但是我應該逐字地進行復制。 我嘗試了這段代碼,但是當我運行此代碼時,我的輸出文件最終將每個單詞放在換行符上。 我應該如何逐個單詞地將內容從一個文件復制到另一個文件?
#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;
}
注意:只允許使用fscanf("%s")
從輸入文件中讀取。
PS我也知道這是一種低效的方法,但這是我應該做的。
由於請求僅使用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);
}
此處緩沖區包含一行中的整個字符串,因此您可以將整行寫入輸出文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.