Bladeren bron

core: use Stat to get file size

Daniele Bartolini 6 jaren geleden
bovenliggende
commit
b612e23478
3 gewijzigde bestanden met toevoegingen van 31 en 10 verwijderingen
  1. 3 10
      src/core/filesystem/filesystem_disk.cpp
  2. 23 0
      src/core/os.cpp
  3. 5 0
      src/core/os.h

+ 3 - 10
src/core/filesystem/filesystem_disk.cpp

@@ -89,16 +89,9 @@ struct FileDisk : public File
 	{
 		CE_ASSERT(is_open(), "File is not open");
 #if CROWN_PLATFORM_POSIX
-		long pos = ftell(_file);
-		CE_ASSERT(pos != -1, "ftell: errno = %d", errno);
-		int err = fseek(_file, 0, SEEK_END);
-		CE_ASSERT(err == 0, "fseek: errno = %d", errno);
-		long size = ftell(_file);
-		CE_ASSERT(size != -1, "ftell: errno = %d", errno);
-		err = fseek(_file, (long)pos, SEEK_SET);
-		CE_ASSERT(err == 0, "fseek: errno = %d", errno);
-		CE_UNUSED(err);
-		return (u32)size;
+		Stat stat;
+		os::stat(stat, fileno(_file));
+		return (u32)stat.size;
 #elif CROWN_PLATFORM_WINDOWS
 		return GetFileSize(_file, NULL);
 #endif

+ 23 - 0
src/core/os.cpp

@@ -84,6 +84,29 @@ namespace os
 #endif
 	}
 
+#if CROWN_PLATFORM_POSIX
+	void stat(Stat& info, int fd)
+	{
+		info.file_type = Stat::NO_ENTRY;
+		info.size = 0;
+		info.mtime = 0;
+
+		struct stat buf;
+		memset(&buf, 0, sizeof(buf));
+		int err = ::fstat(fd, &buf);
+		if (err != 0)
+			return;
+
+		if (S_ISREG(buf.st_mode) == 1)
+			info.file_type = Stat::REGULAR;
+		else if (S_ISDIR(buf.st_mode) == 1)
+			info.file_type = Stat::DIRECTORY;
+
+		info.size = buf.st_size;
+		info.mtime = buf.st_mtime;
+	}
+#endif
+
 	void stat(Stat& info, const char* path)
 	{
 		info.file_type = Stat::NO_ENTRY;

+ 5 - 0
src/core/os.h

@@ -62,6 +62,11 @@ namespace os
 	/// Logs the message @a msg.
 	void log(const char* msg);
 
+#if CROWN_PLATFORM_POSIX
+	/// Returns information about @a fd.
+	void stat(Stat& info, int fd);
+#endif
+
 	/// Returns information about @a path.
 	void stat(Stat& info, const char* path);