C++编程中设置文件长度的方法

转自:http://blog.csdn.net/rrrfff/article/details/6705685

 1 bool SetFileLength(const char *FilePath, off_t Length)  
 2 {  
 3 #ifdef WIN32  
 4     System::IO::FileStream *File = System::IO::File::Open(Length, File::OpenMode, File::AllAccess);  
 5     if (!File)  
 6     {  
 7         return false;  
 8     }  
 9     /// <summary>  
10     /// 表达式调用 File->SetLength() 方法  
11     /// 该方法的底层实现是调用NtSetInformationFile  
12     /// 并通过 FILE_END_OF_FILE_INFORMATION 结构来设置文件长度  
13     /// 该方法的优势是可以直接设置 LONGLONG 型的长度  
14     /// </summary>  
15     File->Length = Length;  
16     delete File;  
17     return true;  
18     //参考资料  
19     //http://msdn.microsoft.com/en-us/library/ff567096(v=VS.85).aspx  
20 #else  
21     int fd = open(FilePath, O_RDWR);  
22     /// <summary>  
23     /// -1 if an error occurred  
24     /// </summary>  
25     if (fd == -1)  
26     {  
27         return false;  
28     }  
29     /// <summary>  
30     /// On success, zero is returned. On error, -1 is returned, and errno is set appropriately.  
31     /// </summary>  
32     return ftruncate(fd, Length) == 0;  
33     //参考资料  
34     //http://api.taocpp.com/doc/path/linux系统调用/文件读写/ftruncate/  
35     //http://linux.die.net/man/2/ftruncate  
36 #endif  
37 }  

 

posted @ 2017-12-29 17:24  优秀afa  阅读(1951)  评论(0编辑  收藏  举报