-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.c
More file actions
70 lines (49 loc) · 2.02 KB
/
Copy pathfile.c
File metadata and controls
70 lines (49 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Implementation and private data goes here (file.c)
#include "file.h"
#include <stdlib.h>
#include <stdio.h>
// the structure hold every informations needed by HTEXTFILE type
typedef struct {
FILE* pFile; // Hold the file pointer descriptor
char status[32]; // Hold the current status of the object
int text_max_len;
}FILESTRUCT, * PFILESTRUCT;
HTEXTFILE init_file(CONST LPSTR szFile)
{
PFILESTRUCT pFileStruct = NULL; // Declara a pointer to the object and initialize with NULL
pFileStruct = (PFILESTRUCT)malloc(sizeof(FILESTRUCT)); // Create the object in memory dynamically
if (pFileStruct == NULL) // Test if success
return NULL;
// Check the path length
if (strnlen_s(szFile, MAX_PATH) == MAX_PATH)
return NULL;
// Open the file
if (fopen_s(&pFileStruct->pFile, szFile, "a+") != 0)
return NULL;
// Update the status
strcpy_s(pFileStruct->status, sizeof(pFileStruct->status)-1, "Openned");
// Define a maximal characters length to write in the file
pFileStruct->text_max_len = 1000;
// Returning pFileStruct abstracted as HTEXTFILE,
// in this way you hide the struct details implementation and only return pointer to HTEXTFILE
return pFileStruct;
}
BOOL write_file(CONST HTEXTFILE hFile, LPSTR text)
{
if (hFile == NULL) // Check if the object is valid
return FALSE;
PFILESTRUCT pFileStruct = (PFILESTRUCT)hFile; // Cast hFile to the struct object
if(strcmp(pFileStruct->status, "Openned") != 0)
return FALSE;
fwrite(text, sizeof(CHAR), strnlen_s(text, pFileStruct->text_max_len), pFileStruct->pFile); // Write inside the file for a max amount of 1000 characters
return TRUE;
}
BOOL close_file(CONST HTEXTFILE hFile)
{
if (hFile == NULL)
return FALSE;
PFILESTRUCT pFileStruct = (PFILESTRUCT)hFile; // Cast hFile to the struct object
fclose(pFileStruct->pFile); // Close the file
free(pFileStruct); // Free the struct from the allocated memory
return FALSE;
}