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 }  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM