I'm definetly getting into the C wagon, many of you will ask why would I want to get aboard a language that it's certainly difficult to master, and my answer is simple, It's just because most of the software, programming languages, etc that we use today come from this very same language.
Most of today's programming languages such as PHP dont provide the programmer with enough background about memory allocation, etc.
And certainly when it comes to threading, using multiple sockets, nothing beats C!
Being curious enough these days I've learnt about dynamic memory allocation with pointers which is *very* cool. Before I knew dynamic memory allocation I always thought about the problem of fixed size arrays, my thought was something like this
"If I always have to pass the size, that is incredibly stupid, I'm sure theres a way to solve this out, like, if my program would take input from a user, I would like that input to be dynamic and not static! I dont want to force her/him to only be able to write 100 bytes!"
I've been always curious about it and now I really want to get to know it, so here we go!
This is a simple program that illustrates memory allocation, by reading a file of any length. Might have some trouble, but it has definetly worked for me :)
#include <stdio.h>
#include <stdlib.h>
//This is the size of the buffer
#define LENGTH 2048
char* readfile(const unsigned char* path, unsigned long length);
void minimize(char* str);
main(int argc, char* argv[]){
char* cur;
while((cur=readfile(argv[1],LENGTH))!=NULL){
printf("%s",cur);
}
return 0;
}
char* readfile(const unsigned char* path,const unsigned long length){
static FILE* fp;
static unsigned long int offset = 0;
if(!fp){
fp = fopen(path,"r");
}
if(!fp){
puts("Cannot read file");
return 0;
}
if (!fseek(fp,offset,length)){
puts("Done");
fclose(fp);
return NULL;
}
offset+=length;
char* read = malloc(length);
if( (fgets(read,length,fp)) == NULL){
fclose(fp);
return NULL;
}
return read;
}
viernes, 11 de septiembre de 2009
Suscribirse a:
Enviar comentarios (Atom)
No hay comentarios:
Publicar un comentario