1 // Copyright (C) 2002-2012 Nikolaus Gebhardt
2 // This file is part of the "Irrlicht Engine".
3 // For conditions of distribution and use, see copyright notice in irrlicht.h
4 
5 #include "CWriteFile.h"
6 
7 #include "utils/file_utils.hpp"
8 #include <stdio.h>
9 
10 namespace irr
11 {
12 namespace io
13 {
14 
15 
CWriteFile(const io::path & fileName,bool append)16 CWriteFile::CWriteFile(const io::path& fileName, bool append)
17 : FileSize(0)
18 {
19 	#ifdef _DEBUG
20 	setDebugName("CWriteFile");
21 	#endif
22 
23 	Filename = fileName;
24 	openFile(append);
25 }
26 
27 
28 
~CWriteFile()29 CWriteFile::~CWriteFile()
30 {
31 	if (File)
32 		fclose(File);
33 }
34 
35 
36 
37 //! returns if file is open
isOpen() const38 inline bool CWriteFile::isOpen() const
39 {
40 	return File != 0;
41 }
42 
43 
44 
45 //! returns how much was read
write(const void * buffer,u32 sizeToWrite)46 s32 CWriteFile::write(const void* buffer, u32 sizeToWrite)
47 {
48 	if (!isOpen())
49 		return 0;
50 
51 	return (s32)fwrite(buffer, 1, sizeToWrite, File);
52 }
53 
54 
55 
56 //! changes position in file, returns true if successful
57 //! if relativeMovement==true, the pos is changed relative to current pos,
58 //! otherwise from begin of file
seek(long finalPos,bool relativeMovement)59 bool CWriteFile::seek(long finalPos, bool relativeMovement)
60 {
61 	if (!isOpen())
62 		return false;
63 
64 	return fseek(File, finalPos, relativeMovement ? SEEK_CUR : SEEK_SET) == 0;
65 }
66 
67 
68 
69 //! returns where in the file we are.
getPos() const70 long CWriteFile::getPos() const
71 {
72 	return ftell(File);
73 }
74 
75 
76 
77 //! opens the file
openFile(bool append)78 void CWriteFile::openFile(bool append)
79 {
80 	if (Filename.size() == 0)
81 	{
82 		File = 0;
83 		return;
84 	}
85 
86 	File = FileUtils::fopenU8Path(Filename.c_str(), append ? "ab" : "wb");
87 
88 	if (File)
89 	{
90 		// get FileSize
91 
92 		fseek(File, 0, SEEK_END);
93 		FileSize = ftell(File);
94 		fseek(File, 0, SEEK_SET);
95 	}
96 }
97 
98 
99 
100 //! returns name of file
getFileName() const101 const io::path& CWriteFile::getFileName() const
102 {
103 	return Filename;
104 }
105 
106 
107 
createWriteFile(const io::path & fileName,bool append)108 IWriteFile* createWriteFile(const io::path& fileName, bool append)
109 {
110 	CWriteFile* file = new CWriteFile(fileName, append);
111 	if (file->isOpen())
112 		return file;
113 
114 	file->drop();
115 	return 0;
116 }
117 
118 
119 } // end namespace io
120 } // end namespace irr
121 
122