[英]Using fscanf to read an input file fails mid-line
好久不見 我已經做了很多無濟於事的挖掘工作,所以我會正確解決的...
我在C從事一個物理研究項目。 我正在嘗試讀取輸入值文件...每行包含12個以空格分隔的double類型的值,並且輸入文件長1006行。 由於文件輸入是眾所周知的,因此我選擇使用fscanf()來攝取輸入,執行操作以對其進行重新排序,然后將其輸出到另一個更適合gnuplot使用的文件中。 這是問題行和有問題的行之前的行:
2.250000000000000 0.500000000000000 2.668878914693362 0.081121085306632 2.668879345525446 0.081120608880718 0.081120609109235 2.668879508723290 -1.139145600698256 -0.478208465494011 -0.476544273039587 -0.184392862164658
2.250000000000000 0.550000000000000 2.723599351123168 0.076400593002322 2.723599435547186 0.076400582995125 0.076400821024960 2.723599264264542 -0.996035795911154 -0.408011755823990 -0.409827430433329 -0.178196609653836
目前,我要做的只是讀取文件並僅輸出我所關心的內容,然后再添加更多邏輯,但是fscanf()出現了問題。 有關的相關代碼如下(包括調試語句):
int readEOF = 0;
double maxThreePhaseParticleCount = 0.0;
double particlesATotal = 0.0;
double particlesBTotal = 0.0;
double rhoA1 = 0;
double rhoA2 = 0;
double rhoA3 = 0;
double rhoB1 = 0;
double rhoB2 = 0;
double rhoB3 = 0;
FILE * two_phase_coords;
char two_phase_coords_name[255];
sprintf(two_phase_coords_name,"~/threePhaseDiagram-densities-twoPhases_tcA%f_tcB%f_aA%f_aAB%f_aB%f.dat", tcA, tcB, aA, aAB, aB);
two_phase_coords = fopen(two_phase_coords_name, "r");
readEOF = fscanf(two_phase_coords, "%lf %lf %lf %lf %lf %lf %lf %lf %*lf %*lf %*lf %*lf", &particlesATotal, &particlesBTotal, &rhoA1, &rhoB1, &rhoA2, &rhoB2, &rhoA3, &rhoB3);
while (readEOF != EOF) {
readEOF = fscanf(two_phase_coords, "%lf %lf %lf %lf %lf %lf %lf %lf %*lf %*lf %*lf %*lf", &particlesATotal, &particlesBTotal, &rhoA1, &rhoB1, &rhoA2, &rhoB2, &rhoA3, &rhoB3);
printf("just read %i...\n%.15f %.15f %.15f %.15f %.15f %.15f %.15f %.15f %.15f\n", readEOF, particlesATotal, particlesBTotal, maxThreePhaseParticleCount, rhoA1, rhoB1, rhoA2, rhoB2, rhoA3, rhoB3);
}
問題行的第6個字段(1006中的第988行)是東西掉下來的地方...而不是讀出0.076400582995125,而是讀取值0.000000000000000 ... readEOF返回6,而不是預期的8,並且fscanf ()失敗/在下一個循環迭代中返回EOF。
我很困惑。 我嘗試過的東西
我將不勝感激,因為我當了C語言大師已經很長時間了。 由於這是我的第一篇SO帖子,因此,如果我不小心踩踏了任何社區期望/禮節,請提前道歉。
謝謝您的幫助!!
因此,我不確定這種情況發生的頻率,但是自然而然地,在我發布此問題之后,我便設法跟蹤正在發生的事情...所討論的功能是較大環境的一部分,並且對該功能的調用是在指向輸入文件的文件指針已關閉(未定義的行為)。 我想自己投反對票。
謝謝大家的指教!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.