Click to See Complete Forum and Search --> : files


Hyena
May 18th, 1999, 12:03 PM
i'm just beginning files, and am in need of help. program makeword (below) simply saves an inputted word to a file. readword should read this file and print out the word, but it doesn't work. help



//program makeword- makes a word and stores it in a file

#include <stdio.h>
#include <iostream.h>

void main()
{
FILE *fPtr;


fPtr = fopen("a:\word.dat", "w");

char *word = new char[30];

cout << "Enter a word: ";
scanf("%s",word);
fprintf(fPtr, "%s", word);


fclose(fPtr);
}

//============================================================//



//program readword- reads data from makeword
#include <iostream.h>
#include <stdio.h>

void main()
{
FILE *fPtr;
char *word = new char[30];

fPtr = fopen("a:\words.dat","r");

fscanf(fPtr,"%s", word);
printf("%s",word);

fclose(fPtr);
}

chiuyan
May 18th, 1999, 12:20 PM
the string "a:\word.dat" should probably be "a:\\word.dat", are you checking to make sure the fPtr is a good pointer before you try to read from it?

--michael

May 18th, 1999, 12:39 PM
First of all be aware that you are mixing C and C++, which is ok if you know what you are doing and why you are doing it. My suggestion is to learn C++ and because C is a subset of C++ it will be easier to learn C later if need be.
The suggestion you got to double up on the back slash character in the path string is correct. Also (as noted) always test your file pointers for NULL after a call to fopen. EX. if (fPtr == NULL) perror("Can't open file");
In C++ you would enclose IO function calls in a try/catch block, but that is a lesson that will come later down the road for you.