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