Structured Programming

FILE MANAGEMENT IN C-EXAMPLES 
Compiling on MAC using the console: 
Since X-code is very heavy and codeblocks is a bit buggy on a MAC, i chose to use TextWrangler as my text editor and the terminal to compile, debug and run my c-codes. You will need a compiler installed, i use GCC.  First navigate to where your program is stored (Mine was on the desktop). Run the following commands (Replace "fileCreate.c" with your source code name).












2. Creating a document in C using a MAC:
All you will need is change to file extension to reflect what type of file to create.
(Replace  "FileMgt" with your folder name/directory and "ugfile.doc" with your file name and extension)

#include <stdio.h>
int main (void){
//pointer to the file
FILE *filePointer;
/* fopen() takes file name and mode(w, r, a, w+, a+) as parameters */
/*I have also specified a directory on my desktop
where the file will be created */
filePointer = fopen ("FileMgt/ugfile.doc","w");
//writing to a file
fprintf(filePointer, " This is Uganda");
fclose(filePointer);
//main returns an integer and it can be any
return 10; }

3. Reading from a file 
Now i will write a code to read the content that was stored in the file.
#include <stdio.h>

int main (void)
{
//pointer to the file
FILE *filePointer;
// The mode r, reads the file instead of writing to a file
filePointer = fopen ("FileMgt/ugfile.doc","r");
//character array to store the content that will be read
char content[20];
/*Loop up to the end of file (feof), get the content,
store it the array and later output it on the console */
while (!feof(filePointer)){
fgets(content, 20, filePointer);
//Or you ould just use puts()
printf ("%s\n", content);
}
//close the file
fclose(filePointer);
//main returns an integer and it can be any
return 10;
}

Output








No comments:

Post a Comment