我需要收集寫入文本檔案的資料并使用 bash shell,它允許文本檔案的每一行在我的 c 程式中用作單獨的資料點。對于更多的背景關系,我的程式正在為我的 input.txt 檔案中的多行獲取一組坐標(x,y)。之后,它會根據它所在的點找到最近和最遠的點。
例如 input.txt 有以下幾行:
input1 3.2 9.3
input2 5.7 13.6
input3 18.4 12.2
我還沒有找到如何在 bash 上執行此操作。我撰寫了以下程式來做一些非常相似但不是動態使用 bash 重定向的事情。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct coordinates{
//The label of the coordinates
char coordinateName[32];
//The x and y coordinates
float xCoord;
float yCoord;
} coordinate;
//Function to calculate distance from another point
float distance(char p1[32], char p2[32], float x1, float x2, float y1, float y2){
float c;
c = sqrt( pow((x1-x2),2) pow((y1-y2),2) );
printf("\nDistance between %s and %s is: %f", p1, p2, c);
return c;
}
int main (int argc, char *argv[]) {
// Get the number of inputs being taken in from the user via command line
int ENTRIES = atoi(argv[1]);
// Declare a struct object
struct coordinates myCoordinates[ENTRIES];
for(int i = 0; i<ENTRIES; i ){
// Enter the coordinate name
printf("Enter a Coordinate name: ");
scanf("%s", &*myCoordinates[i].coordinateName);
// Ask for x coordinate
printf("Enter a Coordinate value for x: ");
scanf("%f", &myCoordinates[i].xCoord);
// Ask for y coordinate
printf("Enter a Coordinate value for y: ");
scanf("%f", &myCoordinates[i].yCoord);
}
printf("\n");
//define closest and furthest points
float closestPoints = INFINITY, furthestPoints = 0.0;
int closestPoint1, closestPoint2;
int furthestPoint1, furthestPoint2;
//define calculation variable to check against closest and furthest point
float calculation;
for(int i = 0; i <= ENTRIES-1; i ){
for (int j = 0; j <= ENTRIES-1; j ) {
char *p1,*p2;
float x1,x2,y1,y2;
p1 = myCoordinates[i].coordinateName;
x1 = myCoordinates[i].xCoord;
y1 = myCoordinates[i].yCoord;
p2 = myCoordinates[j].coordinateName;
x2 = myCoordinates[j].xCoord;
y2 = myCoordinates[j].yCoord;
//if coord1 is equal to coord2
if(i==j){
continue;
}
else{
calculation = distance(p1, p2, x1, x2, y1, y2);
if (calculation < closestPoints){
closestPoint1 = i;
closestPoint2 = j;
closestPoints = calculation;
}
if (calculation > furthestPoints){
furthestPoint1 = i;
furthestPoint2 = j;
furthestPoints = calculation;
}
}
}
}
printf("\nClosest points from one another is point %s and point %s with a distance of %f", myCoordinates[closestPoint1].coordinateName, myCoordinates[closestPoint2].coordinateName, closestPoints);
printf("\nFurthest points from one another is point %s and point %s with a distance of %f", myCoordinates[furthestPoint1].coordinateName, myCoordinates[furthestPoint2].coordinateName, furthestPoints);
}
任何對此的見解或資料將不勝感激。謝謝
uj5u.com熱心網友回復:
假設 C 代碼被編譯為可執行檔案a.out,請您嘗試 bash 代碼:
#!/bin/bash
./a.out $(wc -l < input.txt) < input.txt > output,txt
$(wc -l < input.txt)計算輸入檔案的行數并a.out作為第一個引數傳遞給。- 被
input.txt重定向到 的標準輸入,a.out輸出被重定向到output.txt作為新檔案創建的 。
C 代碼無需修改即可作業,但可以進行改進,例如洗掉提示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/451484.html
上一篇:帶有前導X字符的日期字串
