Results 1 to 3 of 3
Hello,
I've started learning C a few days ago and I wrote this simple code:
Code:
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
int main(void){
char* tmp = (char*) malloc(sizeof(char));
int counter = 1;
...
- 02-02-2012 #1Just Joined!
- Join Date
- Jul 2010
- Posts
- 26
[C] A better way for memory allocating
Hello,
I've started learning C a few days ago and I wrote this simple code:
Does anyone know a better way to write it without that extra step (the counter)?Code:#include<stdio.h> #include<stdlib.h> #include<fcntl.h> int main(void){ char* tmp = (char*) malloc(sizeof(char)); int counter = 1; int fh = open("file.txt", O_RDONLY); /* Ugly */ while( read(fh, tmp, 1) != '\0' ) counter++; lseek(fh, 0, SEEK_SET); char *buffer = (char*) malloc(sizeof(char) * counter); read(fh, buffer, counter); printf("%s", buffer); free(buffer); buffer = NULL; close(fh); }
- 02-02-2012 #2
All you're doing is malloc'ing enough memory to contain the file - why don't you just check the file size?
Seek the end of the file:
then find the current position of the file pointerCode:fseek(fh, 0L, SEEK_END);
you can then use the 'size' to work out how much memory to allocate. Of course, as it's C, you'll have to declare the 'size' variable before you call ftell(...)Code:long int size = ftell(fh);
Linux user #126863 - see http://linuxcounter.net/
- 02-07-2012 #3
You can also call stat() against the filespec, or fstat() against the open filehandle, passing it a struct stat. The structure will be filled in with all sorts of goodies, including the size of the file, in bytes.
For details:
man 2 stat
--- rod.Stuff happens. Then stays happened.


Reply With Quote