Skip to content

Commit 222d7c9

Browse files
adding new tempfile feature
1 parent 832647b commit 222d7c9

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

code/logic/fossil/io/stream.h

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,15 @@ int32_t fossil_fstream_delete(const char *filename);
278278
*/
279279
int fossil_fstream_get_type(const char *filename);
280280

281+
/**
282+
* Create a temporary file.
283+
*
284+
* This function creates a temporary file and returns its name.
285+
*
286+
* @return A pointer to the name of the temporary file, or NULL on failure.
287+
*/
288+
fossil_fstream_t fossil_fstream_tempfile(void);
289+
281290
/**
282291
* Check if a file is readable.
283292
*
@@ -776,6 +785,17 @@ namespace fossil {
776785
return fossil_fstream_get_type(filename.c_str());
777786
}
778787

788+
/**
789+
* Create a temporary file.
790+
*
791+
* This function creates a temporary file and returns its name.
792+
*
793+
* @return A pointer to the name of the temporary file, or NULL on failure.
794+
*/
795+
static fossil_fstream_t tempfile() {
796+
return fossil_fstream_tempfile();
797+
}
798+
779799
/**
780800
* Check if a file is readable.
781801
*

code/logic/stream.c

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@
2323
#include <windows.h>
2424
#else
2525
#include <unistd.h>
26+
#ifndef _POSIX_C_SOURCE
27+
extern int mkstemp(char *);
28+
#endif
2629
#include <fcntl.h>
2730
#endif
2831

@@ -501,6 +504,34 @@ int32_t fossil_fstream_is_readable(const char *filename) {
501504
#endif
502505
}
503506

507+
fossil_fstream_t fossil_fstream_tempfile(void) {
508+
fossil_fstream_t temp_stream;
509+
char temp_filename[FOSSIL_BUFFER_MEDIUM];
510+
511+
#ifdef _WIN32
512+
if (GetTempFileNameA(".", "fossil", 0, temp_filename) == 0) {
513+
fprintf(stderr, "Error: Failed to create temporary file\n");
514+
return (fossil_fstream_t){NULL, ""};
515+
}
516+
#else
517+
char template[] = "fossil_tempfile_XXXXXX";
518+
int fd = mkstemp(template);
519+
if (fd == -1) {
520+
fprintf(stderr, "Error: Failed to create temporary file\n");
521+
return (fossil_fstream_t){NULL, ""};
522+
}
523+
close(fd); // Close the file descriptor as it's no longer needed
524+
strncpy(temp_filename, template, FOSSIL_BUFFER_MEDIUM);
525+
#endif
526+
527+
if (fossil_fstream_open(&temp_stream, temp_filename, "wb+") != FOSSIL_ERROR_OK) {
528+
fprintf(stderr, "Error: Failed to open temporary file - %s\n", temp_filename);
529+
return (fossil_fstream_t){NULL, ""};
530+
}
531+
532+
return temp_stream;
533+
}
534+
504535
int32_t fossil_fstream_is_writable(const char *filename) {
505536
#ifdef _WIN32
506537
DWORD attrs = GetFileAttributesA(filename);

0 commit comments

Comments
 (0)