/* MPI File I/O Test by Kris Schnee Demonstrates loading and writing text data. */ #include #include "mpi.h" int main(int n_args, char** args) { // Invoke MPI for the hell of it. Not really using it yet. MPI_Init(&n_args, &args); printf("\n\n*** Demo of file I/O ***\n\n"); // Open a file for reading text. FILE* input_file = fopen("input.txt","rt"); if(input_file == NULL) { printf("Error: Couldn't find/open input file \"input.txt\". Create one, if not!\n"); return(1); } printf("Got the file open successfully. Now trying to read and display it line by line.\n"); char line[80]; // Stores up to 80 characters of text from one line of the file. Should be safe from buffer overflow hacks due to the way it's being used. while(fgets(line, 80, input_file) != NULL ) // Try to read a line, ending on a failure. { printf(line); // Since lines end with \n characters, a newline gets printed automatically. } // Note: To convert a string to an int: // int x; // sscanf(input_string,"%d",&x); fclose(input_file); printf("Now trying to write an output file.\n"); // Open an output file for writing. FILE* output_file = fopen("output.txt","w"); // Note: overwrites old content, which is what we want. if(output_file == NULL) { printf("Error: Couldn't open output file.\n"); return(1); } // Write some junk. int i; for(i=0;i<10;i++) { fputs("Some text\n",output_file); } fclose(output_file); printf("Success."); return 0; }