1

我必须制作一个程序来管理它从文件中获取的信息,但我使用的是古老的 Turbo C 3.0,所以我在尝试写入文件时遇到错误,这是我的代码:

#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 作为回报。我知道这一定很简单,但我遇到了问题。

4

4 回答 4

1

Check to make sure you have a valid file:

// 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");
}
于 2012-07-02T04:41:25.523 回答
0
'include statements

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

  getch();

}
于 2013-03-07T16:30:55.957 回答
0

You open the file in write only mode ("w"), but you are trying to read the file with fgetc.

Either open the file in read-only mode ("r"), then read the data, close the file, and open it again in write only mode to write it. Or open the file in a mode that support both reading and writing - check the documentation of Turbo-C for more info.

于 2012-07-02T04:37:14.880 回答
0

Try opening the file for "read" instead:

#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;
}

If it still fails, tell us the error#.

于 2012-07-02T04:43:11.593 回答