Reputation: 91
I have to make a program that manages info it obtains from a file, but I'm using Turbo C 3.0 which is ancient, so I'm getting errors trying to write to the file, here is my code:
#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();
}
Whenever I print it I get -1 as return. I know this must be something really simple but I'm having issues.
Upvotes: 1
Views: 6835
Reputation: 1
'include statements
main(){
char we;
char intt;
ifstream q("xyz.txt");
for (we=0;we<100;we++){
q >> intt;
printf("%c",q);
}
getch();
}
Upvotes: 0
Reputation: 121759
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#.
Upvotes: 0
Reputation: 95355
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");
}
Upvotes: 1
Reputation: 56819
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.
Upvotes: 0