Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Write and read in a Textfile 1

Status
Not open for further replies.

lordhaenchen

Programmer
Apr 25, 2001
6
0
0
CH
How can I write and read in a TExtfile (*.txt), like I would work with a Database
 
I'm not sure this is what you want, but anyway:

#include <string.h>
#include <stdio.h>

int main(int argc, char* argv[])
{
// this file will be open for appending
FILE *f = fopen(&quot;C:\\MyFileName.txt&quot;, &quot;ab&quot;);
if (!f)
{
printf(&quot;Could not open file!\n&quot;);
return -1;
}

const char *data = &quot;This is file data&quot;;
unsigned int dataSize = strlen(data);

// the write process
if (dataSize != fwrite(data, 1, dataSize, f))
{
printf(&quot;Could not write data to file!\n&quot;);
fclose(f);
return 666;
}

// if you want to read from a file:
// #define BUFFERSIZE 1024
// char *readData = new char[BUFFERSIZE];
// fread(readData, 1, BUFFERSIZE, f);
// if you know exactly what amount (size) of data should be read
// from the file you could do:
// char *readData = new char[amount];
// if (amount != fread(readData, 1, ammount, f))
// {
// printf(&quot;Could not read file data!\n&quot;);
// fclose(f);
// return -2;
// }

// this is a &quot;virtual&quot; function that you could call to process
// the data you read from the file
// ProcessData(readData);.


printf(&quot;File data appended!\n&quot;);

fclose(f);

return 0;
}

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top