0

I am trying to store data from two variables in a text file .. and then try to get the data back and output it on screen but somehow the following program is not working as supposed to be.

I first enter data in the two variables n1 and n2 .
then i open the file to write data to it ..
then i open the file again to read data from it .. (but data isnt outputted well)

#include<stdio.h>
int main()
{
	char buffer[3];
	int n1, n2;
	scanf("%d",&n1);
	scanf("%d",&n2); 
	FILE *input =fopen("lilly.txt","w+");
	fprintf(input, "%d\n", n1);
	fprintf(input, "%d\n", n2);
	fclose(input);
	
	FILE *output =fopen("lilly.txt","r");
	printf("\n\nN1          = ");
	fgets(buffer, 0, output);
	printf("%s", buffer);
	printf("\n\n1N2 = "); 
	fgets(buffer, 1, output);
	printf("%s", buffer);
	fclose(output);
	getchar();
	getchar();
	return 0;
}

Edited by terence193: n/a

2
Contributors
3
Replies
5
Views
5 Years
Discussion Span
Last Post by zeroliken
1

try using fscanf when reading a file, you can use google if your not familiar on using fscanf

Edited by zeroliken: n/a

0

Thanks @zeroliken..
Managed to get program to work well..


I couldnt understand what was wrong though in my first attempt.

Edited by terence193: n/a

0

The integer part of fgets is used for the maximum number of characters to be read (including the final null-character). Usually, the length of the array passed as str is used.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.