我有這個代碼:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* ptr = fopen("data.txt","r");
char filename[100];
if (ptr==NULL)
{
printf("no such file.");
return 0;
}
char buf[100];
while (fscanf(ptr,"%*s %*s %s ",buf)==1)
printf("%s\n", buf);
printf("Create a file \n");
scanf("%s", filename);
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}
}
它將完整內容從一個檔案復制到另一個檔案。我只需要復制5最后一個字符(3 列)的字串
例如 Data.txt 看起來像這樣:
Alex 10B 4
John 10A 3
Kate 10C 5
在我將在執行期間創建的檔案中,只能復制Kate 10C 5字串。我已經嘗試了幾個小時,但我不知道該怎么做。你能幫助我嗎?
uj5u.com熱心網友回復:
在每一行的末尾有一個換行符, ( \n) 您可以使用它來逐行讀取并僅復制您想要的:
FILE* dest = fopen("out.txt", "w "); // supressed null check for simplicity
char buf[100];
char* char_to_find;
// parse line by line
while (fscanf(ptr, "
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/361321.html
上一篇:收縮時重新分配堆損壞
下一篇:輸出字串的遞回函式
