Simple File i/o routines

wavsyntax -1 Tallied Votes 98 Views Share

This is my file manipulation library.

[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]
niXman 0 Light Poster

Nonsense!

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

You don't need those loops in readb() and writeb(). All it takes is one line of code, using fread() and fwrite().

niXman 0 Light Poster

There a lot of things too much. And almost half of lines of code errors.
PS
this code could go here? ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.