2012-07-02 42 views
0

我必須製作一個程序來管理它從文件中獲得的信息,但是我使用的是古老的Turbo C 3.0,所以我在嘗試寫入文件時出現錯誤,這裏是我的代碼:使用Turbo C處理文件

#include <conio.h> 
#include <stdio.h> 

void main(){ 
clrscr(); 

int c; 
FILE *datos; 

datos = fopen("datos.txt","w"); 

c = fgetc (datos); 

printf("%d",c); 

fclose(datos); 

getch(); 
} 

每當我打印它,我得到-1作爲返回。我知道這一定很簡單,但我有問題。

+0

爲什麼用'w'(寫入模式)而不是'r'(讀取模式)打開文件? – osgx

+0

@osgx因爲最終我會寫入文件 –

+0

爲什麼你使用Turbo C 3.0? (我學會了使用Turbo C自己進行編程,但那是很久以前的...) –

回答

0

您以只寫模式打開文件("w"),但您試圖使用fgetc讀取文件。

以只讀模式打開文件("r"),然後讀取數據,關閉文件並以只寫模式再次打開文件以寫入文件。或者以支持讀寫的模式打開文件 - 查看Turbo-C的文檔以獲取更多信息。

+0

我將要最終寫入文件,我已將它更改爲'r',但它仍然不起作用 –

+3

@IsaacGonzalez一旦用寫模式打開文件,其中就不會有數據被截斷。可能是你應該添加一些數據,然後再試一次。 – Rohan

1

檢查以確保你有一個有效的文件:

// use "r" for reading, "w" for writing 
datos = fopen("datos.txt", "r"); 

if (datos) 
{ 
    int ch = fgetc(datos); 
    if (ch != EOF) 
     printf("%d\n", c); 
    else 
     printf("End of file!\n"); 
} 
else 
{ 
    printf("Failed to open datos.txt for reading.\n"); 
} 
0

嘗試打開該文件的「讀」,而不是:

#include <conio.h> 
#include <stdio.h> 
#include <errno.h> 

int main(){ 

    int c; 
    FILE *datos; 

    clrscr(); 
    datos = fopen("datos.txt","r"); 
    if (!datos) { 
    printf ("Open failed, errno=%d\n", errno); 
    return 1; 
    }  
    c = fgetc (datos); 
    printf("%d",c); 
    fclose(datos); 
    getch(); 
    return 0; 
} 

如果仍不能成功,告訴我們錯誤#。

+0

它似乎並沒有失敗,我只是得到一個0回報 –

+0

我不小心擦掉了我的代碼中的東西,現在我得到'文件結束了!'作爲輸出,文件的內容是「1234567890」 –

0
'include statements 

main(){ 
    char we; 
    char intt; 
    ifstream q("xyz.txt"); 
    for (we=0;we<100;we++){ 
    q >> intt; 
    printf("%c",q); 
    } 

    getch(); 

}