Created
September 29, 2013 02:00
-
-
Save CSEmbree/6748668 to your computer and use it in GitHub Desktop.
Example file open, parsing, and manipulation, and saving
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Example opening and parsing a *.txt file | |
// | |
//COMPILING: "gcc -g FileManipulation.c -o fm" | |
//RUNNING: "/.fm abc.txt" | |
#include "FileManipulation.h" | |
int main(int argc, char **argv) | |
{ | |
//choose some filename and openmode | |
char* fileName = "abc.txt"; | |
char* mode = "r"; //read | |
if(argc>=2) | |
fileName = argv[1]; | |
//open a file and read it's contents | |
FILE *fp = GetFile( fileName, mode ); | |
if( fp == NULL ) { | |
printf( "An error occured opening file: %s\n", fileName ); | |
return ERROR; | |
} | |
//print contents of the file we have opened | |
if( DisplayFileContents(fp) == ERROR) | |
printf("An error occured when displaying file: %s\n", fileName); | |
return SUCCESS; | |
} | |
//open and return a file pointer based on mode | |
FILE* GetFile(char* fileName, char* mode) | |
{ | |
FILE *fp = fopen( fileName, mode ); | |
return fp; | |
} | |
//read and display a file line by line | |
int DisplayFileContents(FILE *file) | |
{ | |
int bufferSize = 256; | |
char* buffer = malloc(sizeof(char)*bufferSize); | |
int lineCount=0; | |
while( fscanf(file, "%s", buffer) != EOF ) | |
{ | |
printf("%d :: %s\n", lineCount, buffer); | |
lineCount++; | |
memcpy(buffer, "\0", bufferSize); //clear buffer each parse | |
} | |
printf("\n"); //formatting | |
//clean up | |
free(buffer); | |
return SUCCESS; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Example opening and parsing a *.txt file | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
//success or error return values | |
#define SUCCESS 0 | |
#define ERROR -1 | |
//prototypes | |
FILE* GetFile(char *fileName, char* mode); | |
int DisplayFileContents(FILE *file); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment