我想從文本文件中讀取數據並寫入其中,但每次執行我的代碼時,文本文件都沒有任何反應。通過「沒有任何反應」,我的意思是程序不會讀取我的輸入文件,也沒有數據導出到我的輸出文件中。有人能指出它爲什麼不起作用嗎?感謝您提前給予的任何幫助。這裏是我的代碼:C編程文件I/O
#include <stdio.h>
#include <stdlib.h>
FILE *inptr, *outptr;
int main() {
int a, b, c;
inptr = fopen("trianglein.txt","r"); //Initialization of pointer and opening of file trianglein.txt
outptr = fopen("triangleout.txt","w"); //Initialization of pointer and opening of file triangleout.txt
while((fscanf(inptr,"%d %d %d",&a, &b, &c))!= EOF){
fprintf(outptr,"\n%2d %2d %2d\n",a,b,c);
if(a+b>c && b+c>a && c+a>b){
fprintf(outptr, "This is a triangle.\n");
if(a !=b && b !=c && a!=c){
fprintf(outptr, "This is a scalene triangle.\n");
if(a==b && a==c && c==b){
fprintf(outptr, "This is an equilateral triangle.\n");
if(a*a+b*b==c*c || b*b+c*c==a*a || a*a+c*c==b*b){
fprintf(outptr, "This is a right trianlge.\n");
}
}
}
}
}
return 0;
}
trianglein.txt
內容:
10 12 15
2 3 7
3 4 5
6 9 5
6 6 6
6 8 10
7 7 9
它似乎爲我工作。就像我在運行時一樣,triangleout.txt包含了東西。你可以發佈你的trianglein.txt的內容嗎? (你也許想重新看看你的邏輯,因爲直角三角形不是等邊三角形。) – FDinoff
順便說一句,你可能想用「繼續」來重構你的代碼 - 這會讓你避免大量的縮進 – thejh
如果什麼都沒有發生那麼在工作目錄中沒有文件「trianglein.txt」。檢查返回fopen。把文件放在工作目錄下,如果是這種情況。同時檢查「trianglein.txt」的內容。使用調試器是個好主意btw。 – kotlomoy