| | |
Simple File i/o routines
[code] #include <iostream> #include <sys/stat.h> //Detect whether a file exists bool existsf(char file[]){ struct _stat buff; if(!_stat(file,&buff)){ return true; } else{ return false; } } //count bytes int countfb(char file[]){ struct _stat buff; _stat(file,&buff); return buff.st_size; } //Read binary void readfb(char file[],char buffer[],int fsize){ FILE *f=fopen(file,"rb"); int check=0; int count=0; check=fgetc(f); while(count<fsize){ buffer[count]=(char)check; check=fgetc(f); count++; } buffer[count]='\0'; fclose(f); } Write binary void writefb(char file[],char str[],int fsize){ FILE *f=fopen(file,"wb"); int count=0; while(count<fsize){ fputc(str[count],f); count++; } fputc(str[count],f); fclose(f); } //Count the number of chars in a file int countf(char file[]){ FILE *f=fopen(file,"rb"); int check=0; int count=0; check=fgetc(f); while(check>0){ count++; check=fgetc(f); } fclose(f); return count; } //Read file void readf(char file[],char*buffer){ FILE *f=fopen(file,"rb"); int check=0; int count=0; check=fgetc(f); while(check>0){ buffer[count]=(char)check; check=fgetc(f); count++; } buffer[count]='\0'; fclose(f); } //Write to a file int writef(char file[],char string[],char* mode="wb"){ FILE *f=fopen(file,mode); int count=0; while(string[count]!=0){ fputc(string[count],f); count++; } fputc(string[count],f); fclose(f); return count; } //Append text to a file int appendf(char* file,char* text){ char data[countf(file)+1]; readf(file,data); std::string newd; newd=text; newd+=data; writef(file,(char*)newd.c_str()); return 0; } [/code]
0
•
•
•
•
You don't need those loops in readb() and writeb(). All it takes is one line of code, using fread() and fwrite().
Similar Threads
- Code Snippet: A few sorting routines (Java)
- recursive routines (Pascal and Delphi)
- Interrupt Service Routines (Computer Science)
- jwSMTP c++ email routines, worked with it? (C++)
- Code Snippet: Comparing Sorting Routines (C)
| Thread Tools | Search this Thread |
addition api array base based binary bitmap c++ c/c++ char class classes code coding compile console conversion count delete deploy desktop developer directshow dll download dynamic dynamiccharacterarray email embed encryption error erroraftercompilation excel file forms fstream function functions game getline givemetehcodez gmail graph gui homework homeworkhelp homeworkhelper iamthwee ifstream input int integer java lib linkedlist linker loop looping loops map math matrix matrix3d memory multiple news node output parameter pointer problem program programming project python random read recursion reference rpg std::coutwstring string strings temperature template test text text-file tree url variable vector video visualization win32 windows winsock word wordfrequency wxwidgets




