Char d_name [1] member of struct dirent

Source: Internet
Author: User

Description of the last member d_name of the folder attribute struct dirent (refer to the online document) to store the file name. Some UNIX-like systems also use the following definition:

Struct dirent {
Ino_t d_ino;
Off_t d_off;
Unsigned short d_reclen;
Char d_name [1];
};

Obviously, for an array used to store strings, one byte space can only store one Terminator '\ 0'. The purpose of this operation is to use struct dirent to apply for memory space, d_name can be applied on demand without the need to open up 256 bytes of memory at a time. The following is an example:

# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>

Struct dirstruct {
Int Len;
Char name [1];
};
Void main (){
Char fname [256];
Struct dirstruct * pdir;
Printf ("input a file name :");
Gets (fname );
Pdir = (struct dirstruct *) malloc (sizeof (struct dirstruct) + strlen (fname ));
Pdir-> Len = strlen (fname );
Memcpy (& pdir-> name [0], fname, pdir-> Len );
Printf ("Name: % s, Length: % d \ n", pdir-> name, pdir-> Len );
Free (pdir );
}

In this way, you can add the d_name space when instantiating the struct, which is more flexible in processing and saves more memory space.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.