reading a number from a file
Q(1);
This is my code for reading in a number and storing it in a file.
but when i go to print out the number from the file it wont work.does anyone know why.
Q(2);
when the number is stored in a file it is stored as a string. How do i convert the string into a int value.
void main()
{
FILE *fp;
char num[2];
char number[2];
printf("Enter Number");
scanf("%s",&number);
fp=fopen("file.txt","r+");
if(fp==NULL)
puts("Error in opening file.txt");
else
{
puts("file.txt is opened");
fputs(number,fp);
fgets(num,2,fp);
printf("%s",num);
fclose(fp);
}
}
Re: reading a number from a file
Quote:
Originally posted by the_head
Q(1);
This is my code for reading in a number and storing it in a file.
but when i go to print out the number from the file it wont work.does anyone know why.
Q(2);
when the number is stored in a file it is stored as a string. How do i convert the string into a int value.
Use the code tags around the entire program ;)
void main()
{
FILE *fp;
char num[2];
char number[2];
printf("Enter Number");
scanf("%s",&number);
fp=fopen("file.txt","r+");
if(fp==NULL)
puts("Error in opening file.txt");
else
{
puts("file.txt is opened");
fputs(number,fp);
fgets(num,2,fp);
printf("%s",num);
fclose(fp);
}
}
Q1) you cannot write then read the file. After writing, close then open the file for reading.
Also, when inputting data into a string, use fgets() instead of scanf(), you'll have fewer problems with your input.
Q2) in the file or after reading as a string?
If in the file, convert to an integer using atoi() before writing then output using fwrite(). Your file is now a binary file, not text.
If after reading the string from the file, use atoi() and you have an int.