[英]filling in one text file with values from another text file
我有以下文本文件results.txt:
x y u v
3 2 10 12
3 3 10 15
3 4 11 15
5 1 10 12
5 2 12 13
5 3 9 9
現在,我想從上面的文件中獲取值u和v,並將它們放入另一個文件中,其中x從2到5,y從1到5,這樣我就可以獲得所需的輸出:
2 1
2 2
2 3
2 4
2 5
3 1
3 2 10 12
3 3 10 15
3 4 11 15
3 5
4 1
4 2
4 3
4 4
4 5
5 1 10 12
5 2 12 13
5 3
5 4
5 5
為了在上面的輸出中生成x和y值,我只需要使用如下所示的循環:
#include <stdlib.h>
#include <stdio.h>
int main() {
float lat,lon;
int count;
count=1;
for ( lat = -70; lat <= 80; lat = lat + .125){
for ( lon = -179.875; lon <= 180; lon = lon + 0.125){
printf("%d) Value of lat/lon: %0.2f/%0.2f\n", count,lat,lon);
count=count+1;
if (xx= x && yy = y){
printf("%d %d %f %f\n",xx,yy,u,v)
}
else
{
printf("%d %d\n",x,y)
}
}
}
}
在上述c程序代碼段的上下文中,我如何讀取文件以及上面的循環,以便當上述循環中的x和y值組合與results.txt中的x和y組合匹配時( xx和yy)插入它會打印來自results.txt文件的相應行? 如何使用適當的read語句調整上面的程序以獲得所需的輸出結果?
好的,讓我告訴您,我不理解您想如何使用示例代碼。 似乎與您的問題無關:
用另一個文本文件中的值填充一個文本文件
如果你已經有了充滿results.txt
以及要填寫第二個文件(我們稱之為second.txt
)為您定義的,那么你可以如下做到這一點:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* fp;
int x, y, i;
char found = 0;
int results[1024][4] = {};
int rows = 0;
/* Open the results.txt for read. */
fp = fopen("results.txt", "r");
if(fp == NULL)
exit(EXIT_FAILURE);
/* Parse results.txt line-by-line and store the values to results array. */
while(fscanf(fp, "%d %d %d %d\n",
&results[rows][0], &results[rows][1],
&results[rows][2], &results[rows][3]) == 4 && rows < 1024) {
printf("x: %d, y: %d, u: %d, v: %d\n", results[rows][0],
results[rows][1], results[rows][2], results[rows][3]);
rows++;
}
fclose(fp);
/* Open the second.txt for write. */
fp = fopen("second.txt", "w");
if(fp == NULL)
exit(EXIT_FAILURE);
for(x = 2; x <= 5; ++x) {
for(y = 1; y <= 5; ++y) {
found = 0;
/* Search for matching entry in results array. */
for(i = 0; i < rows; ++i) {
if(results[i][0] == x && results[i][1] == y) {
found = 1;
break;
}
}
if(found)
fprintf(fp, "%d %d %d %d\n", x, y, results[i][2], results[i][3]);
else
fprintf(fp, "%d %d\n", x, y);
}
}
fclose(fp);
exit(EXIT_SUCCESS);
}
上面的示例未經優化,但經過測試可以正常工作。 在results.txt
它最多只能有1024行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.