Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I have a pretty simple question about reading and writing from a text file. I don't even know if I should be attempting this just yet, as I am really not familiar with pointers(although I'm not sure if they have anything to do with what I want to do).
I want this program to input a simple string from a user and write it to a file. I will stick with just writing to the file for now, and perhaps later in the thread, to reading from a file.
I am going to outline what I want to accomplish in psuedo-code. If someone could "translate" this to C/C++ or Python, I would appreciate it. Also, feel free to offer any other advice on this. Thanks.OPEN (something.txt)
PRINT "Enter some text"
INPUT x
WRITE x(something.txt)
CLOSE (something.txt)
END

char string[80];
char buffer[80];ifstream inFile;
ofstream outFile;cout [[ "Enter a string";
cin.getline(string, 80, '\n');outFile.open("somefile.ext", ios::out);
error check
outFile [[ string;
inFile.open("somefile.ext", ios::in);
error check
inFile.getline(buffer, 80, '\n');
cout [[ buffer;
piece of cake ;-)

Thanks Roninl. But I am not familiar with most of that code. I obviously have a bit more to learn. Also, I assume from the dot notation that inFile and outFile are objects. Right? How would one do this without working with objects? How about in just regular C as opposed to C++?

NP
I'm not an expert in OOP, but I presume ofstream and ifstream are simply objects in the fstream class.
C file i/o is a little more involved and I often have to think about it before I try it so this is likely not the best route, but I'll give it a shot. That's why I tend to use C++ and C :P
char string[80];
char buffer[80];FILE *fptr;
printf("Enter a string: ");
fgets(string, 80, stdin);if((fptr = fopen("somefile.ext", "w")) == NULL)
{
printf("unable to write to file.");
return -1;
}fprintf(fptr, "%s", string);
fclose(fptr);if((fptr = fopen("somefile.ext", "r")) == NULL)
{
printf("Unable to read from file.");
return -1;
}fgets(buffer, 80, fptr);
fclose(fptr);printf("your string: %s", buffer);
Something like that. Look at your compiler documentation or help files for file i/o
HTH

Thanks again for the reply. Now I can plainly see I am not ready for this yet. I have some more reading to do.

![]() |
VB6 Textbox help
|
a generator app
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |