Find the answer to your Linux question:
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; ...
  1. #1
    Just 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:

    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);
    
    }
    Does anyone know a better way to write it without that extra step (the counter)?

  2. #2
    Trusted Penguin Roxoff's Avatar
    Join Date
    Aug 2005
    Location
    Nottingham, England
    Posts
    3,392
    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:
    Code:
    fseek(fh, 0L, SEEK_END);
    then find the current position of the file pointer
    Code:
    long int size = ftell(fh);
    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(...)
    Linux user #126863 - see http://linuxcounter.net/

  3. #3
    Linux Newbie theNbomr's Avatar
    Join Date
    May 2007
    Location
    BC Canada
    Posts
    150
    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...