| | |
Simple File i/o routines
Please support our C++ advertiser: Intel Parallel Studio Home
[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]
-7
•
•
•
•
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 |
Tag cloud for C++
api application array arrays assignment beginner binary bitmap c++ c/c++ calculator char char* class classes code coding compile compiler console conversion convert count data database delete developer display dll dynamiccharacterarray email encryption error file format forms fstream function functions game generator getline givemetehcodez graph iamthwee ifstream image input int java lib list loop looping loops map math matrix memory multidimensional multiple newbie news node number numbertoword output pointer problem program programming project python random read recursion recursive reference return rpg sorting string strings struct template templates text tree url variable vector video visual visualstudio win32 windows winsock word wordfrequency wxwidgets




