

#include <fstream.h>
#include <iostream.h>
int main() {
char str[10];
ofstream a_file("example.txt");
//Creates an instance of ofstream, and opens example.txt
a_file<<"This text will now be inside of example.txt";
//Outputs to example.txt through a_file
a_file.close();
//Closes up the file
ifstream b_file("example.txt");
//Opens for reading the file
b_file>>str;
//Reads one string from the file
cout<<str;
//Should output 'this'
b_file.close();
//Do not forget this!
}
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
char line[100];
/* open "example.txt" for writing and reading */
if ((fp = fopen("example.txt", "w+")) ==NULL) {
printf("Error opening file\n");
return 1;
}
/* write a line of text to a file called "example.txt" */
fprintf(fp,"This is some text that will go into example.txt\n");
fprintf(fp,"This is some more text that will go into example.txt\n");
/* Reset file pointer to beginning of file */
fseek(fp,0L,SEEK_SET);
/* read/display "example.txt" */
while ( fgets(line,sizeof(line),fp) != NULL ) {
printf("%s",line);
}
/* close "example.txt" file */
fclose(fp);
return 0;
}

Users browsing this forum: No registered users and 2 guests