C++/FILE
Expert: Prince M. Premnath - 4/30/2009
QuestionQUESTION: Hi
i want to create a file in Drive C and write data in it for this purpose i have written the code below but it doesn't work
could you plz help me and tell me what's the problem with my code?
thanx
Bita
ANSWER: hi dear !
post the code ill fix the bug's
Thanks and Regards !
Prince M. Premnath
---------- FOLLOW-UP ----------
QUESTION: Here is the code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
FILE*fp;
void wrfile1();
void main(){
wrfile1();
}
void wrfile1(){
char word[10];
fp=fopen("c:\\text","w");
while(!feof(fp)){
fscanf(fp,"%s",word);
printf("%s",word);
}
printf("\n");
fclose(fp);
}
ANSWER: hi Good Morning!
nothing wrong with your code , you must have opened your file in "r" read mode instead of "w" mode.
Here is your code with minor modification!
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
FILE*fp;
void wrfile1();
void main(){
wrfile1();
}
void wrfile1(){
char word[10];
fp=fopen("c:\\temp\\text","r");
while(!feof(fp)){
fscanf(fp,"%s",word);
printf("%s",word);
}
printf("\n");
fclose(fp);
}
Option 2:
I ve programmed the same programme using the getc() function check out this code as well.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
FILE*fp;
void wrfile1();
void main(){
wrfile1();
}
void wrfile1()
{
char ch;
fp=fopen("c:\\temp\\text","r");
while((ch =getc(fp))!= EOF)
printf("%c" , ch);
fclose(fp);
}
Note: Both programme assumes that the file 'text' is non-empty and existing!
get back to me in case of issues.
Thanks and Regards!
Prince M. Premnath
---------- FOLLOW-UP ----------
QUESTION: thanx for answering
according to your answer the problem that i face every time i run this code should relate to the file that i create in my drive,and the code wants to read from.
could you plz tell me how should i create it?and what's the type of this file?
Thanx
Bita
AnswerHi dear bita !
Sorry for the delay in responding you , since i was busy for the last couple of day's i couldn't respond you !! hum .. am not pretty clear with your ques.
Do you wanna prog that create its own file and read contents from the same ? if so check out the programme given below
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
FILE*fp;
void wrfile1();
void WriteFile();
void WriteFile()
{
FILE * fp = fopen("c:\\temp\\text","w");
fprintf(fp,"%s","this is a sample string ");
fclose(fp);
}
void main(){
WriteFile();
wrfile1();
}
void wrfile1(){
char ch;
fp=fopen("c:\\temp\\text","r");
while((ch =getc(fp))!= EOF)
printf("%c" , ch);
fclose(fp);
}
if not kindly revert me bit clearly to my mail princeatapi@yahoo.co.in, i can answer you much better !
Thanks and Regards!
Prince M. Premnath.