could anyone tell me how to add text to a file?
Printable View
could anyone tell me how to add text to a file?
I didn't try this, but i think it is right.Code:#include <fstream.h>
int main()
{
ofstream file
file.open(anyfile.txt , ios::app)
file<<"use this like cout"<<endl;
file.close();
return 0;
}
cool thanks:)
You can also use the C code (which I think is faster)
FILE* myFile;
int yo;
yo=16;
myFile=fopen("file.txt","rt"); //To open for read access
myFile=fopen("file.txt","wt"); //To open for write access
//YOU CAN ONLY OPEN A FILE ONCE BEFORE YOU CLOSE IT
fprintf(myFile,"Hello, I am %d years old",yo); //to output to the file
fscanf(myFile,"%d",&yo); //to input from a file
fclose(myFile); //Closes the file
--------------------------------------------------------------------
Or, you could use Win32 API code
HANDLE CreateFile(
LPCTSTR lpFileName, // file name
DWORD dwDesiredAccess, // access mode
DWORD dwShareMode, // share mode
LPSECURITY_ATTRIBUTES lpSecurityAttributes, // SD
DWORD dwCreationDisposition, // how to create
DWORD dwFlagsAndAttributes, // file attributes
HANDLE hTemplateFile // handle to template file
);
like this:
HANDLE myFile;
char buffer[100000];
myFile=CreateFile("c:\my documents\hello.txt",GENERIC_READ ¦ GENERIC_WRITE,FILE_SHARE_READ ¦ FILE_SHARE_WRITE,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE _NORMAL,NULL);
and then
BOOL WriteFile(
HANDLE hFile, // handle to file
LPCVOID lpBuffer, // data buffer
DWORD nNumberOfBytesToWrite, // number of bytes to write
LPDWORD lpNumberOfBytesWritten, // number of bytes written
LPOVERLAPPED lpOverlapped // overlapped buffer
);
like this:
WriteFile(myFile,"Hello",5,0,NULL);
and
BOOL ReadFile(
HANDLE hFile, // handle to file
LPVOID lpBuffer, // data buffer
DWORD nNumberOfBytesToRead, // number of bytes to read
LPDWORD lpNumberOfBytesRead, // number of bytes read
LPOVERLAPPED lpOverlapped // overlapped buffer
);
ReadFile(myFile,buffer,100000,0,NULL);
the buffer can be anything since it's a void pointer, such as an int, or a DWORD, or even a struct!!
if you want to find out more about Win32 API File I/O functions, go to http://msdn.microsoft.com , go to Platform SDK, to Win32 API, Reference, Functions by category, File I/O (I think).
good luck
oskilian