file locking
This commit is contained in:
+34
-18
@@ -6,7 +6,8 @@
|
||||
#include <arpa/inet.h>
|
||||
#include <netdb.h>
|
||||
#include <execinfo.h>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <sys/file.h>
|
||||
#include "sys.h"
|
||||
|
||||
String shell_exec(String cmd)
|
||||
@@ -91,33 +92,48 @@ bool file_exists(String path)
|
||||
|
||||
String file_get_contents(String file_name)
|
||||
{
|
||||
try
|
||||
{
|
||||
std::ifstream ifs(file_name);
|
||||
String content(
|
||||
(std::istreambuf_iterator<char>(ifs) ),
|
||||
(std::istreambuf_iterator<char>() ) );
|
||||
return(content);
|
||||
}
|
||||
catch(std::exception e)
|
||||
/*std::ifstream ifs(file_name);
|
||||
printf("stream file desc %i\n", ifs.filedesc());
|
||||
String content(
|
||||
(std::istreambuf_iterator<char>(ifs) ),
|
||||
(std::istreambuf_iterator<char>() ) );*/
|
||||
char buf[512];
|
||||
String content;
|
||||
s32 fd = open(file_name.c_str(), O_RDONLY);
|
||||
if(fd == -1)
|
||||
{
|
||||
printf("(!) Could not read %s\n", file_name.c_str());
|
||||
return("");
|
||||
}
|
||||
flock(fd, LOCK_SH);
|
||||
s64 bytes_read = 0;
|
||||
//s64 size = lseek(fd, 0, SEEK_END);
|
||||
//lseek(fd, 0, SEEK_SET);
|
||||
//content.reserve(size+1);
|
||||
|
||||
while((bytes_read = read(fd, buf, 512)) > 0)
|
||||
{
|
||||
content.append(buf, bytes_read);
|
||||
}
|
||||
|
||||
flock(fd, LOCK_UN);
|
||||
close(fd);
|
||||
return(content);
|
||||
}
|
||||
|
||||
bool file_put_contents(String file_name, String content)
|
||||
{
|
||||
try
|
||||
{
|
||||
std::ofstream out(file_name);
|
||||
out << content;
|
||||
out.close();
|
||||
return(true);
|
||||
}
|
||||
catch(std::exception e)
|
||||
s32 fd = open(file_name.c_str(), O_WRONLY | O_CREAT | O_TRUNC);
|
||||
if(fd == -1)
|
||||
{
|
||||
printf("(!) Could not write %s\n", file_name.c_str());
|
||||
return(false);
|
||||
}
|
||||
flock(fd, LOCK_EX);
|
||||
write(fd, content.data(), content.length());
|
||||
flock(fd, LOCK_UN);
|
||||
close(fd);
|
||||
return(true);
|
||||
}
|
||||
|
||||
String get_cwd()
|
||||
|
||||
Reference in New Issue
Block a user