-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFileUtilities.c
More file actions
1439 lines (1074 loc) · 42.5 KB
/
FileUtilities.c
File metadata and controls
1439 lines (1074 loc) · 42.5 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// FileUtilities.c
// Automated_CSV_Data_Analysis
// DavidRichardson02
#include "FileUtilities.h"
#include "CommonDefinitions.h"
#include "GeneralUtilities.h"
#include "StringUtilities.h"
#include <ctype.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
/**
* determine_file_depth
*
* Calculates the depth of a file in a directory structure based on its path.
* This function counts the number of '/' characters in the file path, assuming a Unix-like file system.
* This function only works with string-based paths and assumes '/' as the directory separator.
*
*
* @param filePathName A string representing the file path.
* @return The depth of the file in the directory hierarchy.
*/
int determine_file_depth(const char* filePathName) //Only works for String-based path.
{
//Simply count the number of '/'.
int depthCount = 0;
for(int i = 0; filePathName[i] != '\0'; i++)
{
if(filePathName[i] == '/')
{
depthCount++;
}
}
return depthCount;
}
/**
* identify_file_extension
*
* Identifies the file extension of a given file path.
* This function uses the `strrchr` function to find the last occurrence of the '.' character,
* which is assumed to be the start of the file extension. This function assumes that the file
* path is a null-terminated string and that the extension is anything following the last '.'
* in the path.
*
* @param filePathName A string representing the file path (i.e., "/home/user/file.txt").
* @return A pointer to the file extension within the given file path, or NULL if no extension is found.
*/
char *identify_file_extension(const char* filePathName) //Only works for String-based path.
{
if(count_character_occurrences(filePathName, '.') == 0) // If this pathname does not have a file extension(ex: a directory pathname)
{
return "\0";
}
//the strrchr function to get the position of the last occurrence of a character in a string.
char *fileExtension = strrchr(filePathName, '.');
return fileExtension;
}
int pathname_has_extension(const char* filePathName)
{
if(count_character_occurrences(filePathName, '.') == 0) // If this pathname does not have a file extension(ex: a directory pathname)
{
return 0;
}
else
{
return 1;
}
}
/**
* find_file_directory_path
*
* Extracts the directory path from a given full file path.
* This function determines the directory path of a file by counting the characters up to the last '/'
* character in the path. It dynamically allocates memory to store the directory path.
* The function assumes Unix-like file paths and uses '/' as the directory separator.
*
* @param filePathName A string representing the full file path.
* @return A dynamically allocated string containing the directory path.
*/
char* find_file_directory_path(const char* filePathName)
{
int fileDepthLevel = determine_file_depth(filePathName);
//Simply count the number of '/'.
int directoryDepthLevel = 0;
int directoryPathNameCharacterCount = 0; //before capturing the actual directory path name that this file is contained inside of, first need to determine how many
//characters the directory path name is from the full path name, i.e., need to count all characters except everything after the last '/'.
//Then, can use this number to allocate memory for a char* of an appropriate size and it will be straightforward to capture the all characters up
//until the cutoff point when the directory that this file is contained in is reached.
for(int i = 0; filePathName[i] != '\0' && directoryDepthLevel != fileDepthLevel; i++) //for loop will terminate as soon as the last '/' is reached.
{
if(filePathName[i] == '/')
{
directoryDepthLevel++;
}
directoryPathNameCharacterCount++;
}
char* directoryPathName;
directoryPathName = allocate_memory_char_ptr(directoryPathNameCharacterCount);
for(int i = 0; i < directoryPathNameCharacterCount; i++)
{
directoryPathName[i] = filePathName[i];
}
return directoryPathName;
}
/**
* find_directory_name_from_path
*
* Extracts and returns the directory name from a given directory path.
* This function takes a directory path as input and determines the directory name
* by analyzing the path string. It identifies the last '/' character and extracts
* the subsequent string as the directory name. This is useful for isolating the
* immediate directory name from a longer directory path.
*
* @param directoryPathName A string representing the directory path.
* @return A dynamically allocated string containing the directory name.
*/
char *find_directory_name_from_path(const char* directoryPathName)
{
//Simply count the number of '/'.
int directoryDepthLevel = 0;
//Count the number of characters in the directory path name.
size_t directoryPathNameCharacterCount = string_length(directoryPathName);
//Count the number of characters in the directory name.
size_t directoryNameCharacterCount = 0;
for(size_t i = directoryPathNameCharacterCount - 1; i >= 0; i--)
{
if(directoryPathName[i] == '/')
{
break; //Stop counting when the last '/' is reached/
}
directoryNameCharacterCount++;
}
char* directoryName;
directoryName = allocate_memory_char_ptr(directoryNameCharacterCount);
for(int i = 0; i < directoryNameCharacterCount; i++)
{
// The value in the bracket is the offset from the first character of the directory name to the first character of the directory path name.
// i is the n_th character of the directory name.
directoryName[i] = directoryPathName[directoryPathNameCharacterCount - directoryNameCharacterCount + i]; // Compute the offset from filepath[0] to the first character of the directory name.
}
return directoryName;
}
/**
* find_name_from_path
*
* Extracts the filename from a given full file path.
* This function isolates the filename from the full path by removing the directory path and the file extension.
* It dynamically allocates memory for the filename. Assumes Unix-like string-based file paths.
*
* @param filePathName A string representing the full file path.
* @return A dynamically allocated string containing the filename.
*/
char* find_name_from_path(const char* filePathName)
{
char* fileExtension = identify_file_extension(filePathName);
char* directoryPathName = find_file_directory_path(filePathName);
/// full path ==
/// directory(.../home/user/...[/filename]) + file name + file extension(.txt, .csv, .dat, etc.)
/// //+ file name + file extension(.txt, .csv, .dat, etc.)
// Determine the length of the file name by subtracting the directory path length and the file extension length from the full path length.
unsigned long filePathLength = strlen(filePathName);
unsigned long fileExtensionLength = strlen(fileExtension);
unsigned long directoryPathLength = strlen(directoryPathName);
unsigned long fileNameLength = filePathLength - (directoryPathLength + fileExtensionLength);
char *fileName;
fileName = allocate_memory_char_ptr(fileNameLength);
for(int i = 0; i < fileNameLength; i++)
{
fileName[i] = filePathName[i+directoryPathLength];
}
return fileName;
}
/**
* count_data_fields
*
* Counts the number of data fields in a CSV-style line.
* This function processes a line from a CSV file and counts the number of fields based on commas.
* It also handles empty fields (i.e., two consecutive commas) by temporarily replacing them with spaces.
* The function assumes that the input string is null-terminated and that the fields are
* separated by commas. It modifies the input string temporarily but restores its original state.
*
* @param lineContents A string representing a line from a CSV file.
* @return The number of data fields in the line.
*/
int count_data_fields(char* lineContents)
{
for(int i = 0; i < strlen(lineContents)+1;i++)
{
if(lineContents[i] == ',' && lineContents[i+1] == ',')
{
lineContents[i] = ' ';
}
}
int count = 0;
// If the header is not empty, start with count 1 (the first field before any comma).
if (lineContents && strlen(lineContents) > 0)
{
count = 1;
}
// Iterate over each character in the string.
for (int i = 0; lineContents[i] != '\0'; i++)
{
// Increment count at each comma, which indicates a new field.
if (lineContents[i] == ',')
{
count++;
}
}
return count;
}
/**
* count_plot_data_fields
*
* Counts the number of fields in a data entry for plotting.
* This function tokenizes a CSV-style line using commas as delimiters and counts the number of tokens.
* It is specifically intended for counting fields in data entries for plotting purposes. This function
* creates a copy of the input line for tokenization and frees it after counting. It prints the token count
* to standard output. Assumes a null-terminated input string and that the data is CSV formatted.
*
* @param lineContents A string representing a line from a CSV file.
* @return The number of fields in the data entry.
*/
int count_plot_data_fields(char* lineContents, const char *delimiter)
{
// Counts the number of fields in a data entry.
int count = 0;
char* dataCopy = strdup(lineContents);
char* token = strtok(dataCopy, delimiter);
while (token)
{
count++;
token = strtok(NULL, delimiter);
}
free(dataCopy);
printf("\n\ncount_plot_data_fields: %d", count);
return count;
}
/**
* count_file_lines
*
* Counts the number of lines in a file.
* This function opens a file specified by its path (filePathName) and counts
* the number of lines it contains, up to a maximum specified by maxLines.
* It uses fgets to read each line into a buffer and increments a counter
* for each line read.
*
* @param filePathName A string representing the path to the file.
* @param maxLines An integer specifying the maximum line length buffer.
* @return The total number of lines in the file.
*/
int count_file_lines(const char* filePathName, int maxLines)
{
//printf("\nEntering: 'count_file_lines' function.\n");
//Open the file at the specified path and ensure file is opened properly.
FILE *tempFile = fopen(filePathName, "r");
if (!tempFile)
{
perror("\n\nError: Unable to open file for 'count_file_lines'.\n");
exit(1);
}
char line[maxLines]; // Buffer to hold each line from the file.
// Count the number of lines in the file from a starting point numLinesToSkip away from the first line.
int count = 0;
while((fgets(line, sizeof(line), tempFile)))
{
count++;
}
if (count >= maxLines)
{
printf("\n\nError: The number of lines in the file '%s' exceeded the expected number of maximum lines, %zu 'count_file_lines'.\n", filePathName, MAX_NUM_FILE_LINES);
perror("\n\nError: File 'count_file_lines'.\n");
exit(1);
}
fclose(tempFile);
return count;
}
/**
* count_file_lines_characters
*
* Counts the characters in each line of a file.
* This function opens a file specified by filePathName and counts the number
* of characters in each line, starting from a specified line (startLine) and
* up to a total number of lines (lineCount). It uses getline for dynamic allocation
* and handling of varying line lengths. The newline character is excluded from the count.
*
* @param filePathName A string representing the path to the file.
* @param lineCount An integer specifying the number of lines to process.
* @return A pointer to an array of integers, each representing the character count of a line.
*/
int* count_file_lines_characters(const char* filePathName, int lineCount)
{
//Open the file at the specified path and ensure file is opened properly.
FILE *tempFile = fopen(filePathName, "r");
if (!tempFile)
{
perror("\n\nError: Unable to open file for 'count_file_lines_characters'.\n");
exit(1);
}
int *fileCharCounts = allocate_memory_int_ptr(lineCount); //allocate memory to store the number of characters for each line.
// Initialize the array with zeros.
for (int i = 0; i < lineCount; i++)
{
fileCharCounts[i] = 0;
}
// Declare variables for
char *line = NULL;
size_t len = 0;
ssize_t read;
int currentLine = 0;
// Read each line from the file.
while ((read = getline(&line, &len, tempFile)) != -1 && currentLine < lineCount)
{
// Count characters in the line, excluding the newline character.
for (int i = 0; i < read; i++)
{
if (line[i] != '\n')
{
fileCharCounts[currentLine]++;
}
}
currentLine++;
}
free(line);
fclose(tempFile);
return fileCharCounts;
}
int determine_maximum_line_length(const char* filePathName, int lineCount) // Determines the maximum line length in a file using count_file_lines_characters
{
int *charCounts = count_file_lines_characters(filePathName, lineCount);
int maxLineLength = max_element(charCounts, lineCount);
free(charCounts);
return maxLineLength;
}
int count_characters_in_file_lines(const char* filePathName, int lineCount)
{
int *charCounts = count_file_lines_characters(filePathName, lineCount);
int totalCharacters = sum_elements_int(charCounts, lineCount);
free(charCounts);
return totalCharacters;
}
/**
* count_characters_in_file_lines_range
*
* Counts the characters in each line of a file.
* This function opens a file specified by filePathName and counts the number
* of characters in each line, starting from a specified line (startLine) and
* up to a total number of lines (lineCount). It uses getline for dynamic allocation
* and handling of varying line lengths. The newline character is excluded from the count.
*
* @param filePathName A string representing the path to the file.
* @param lineCount An integer specifying the number of lines to process.
* @param startLine An integer specifying the line number to start counting from.
* @return A pointer to an array of integers, each representing the character count of a line.
*/
int* count_characters_in_file_lines_range(const char* filePathName, int lineCount, int startLine)
{
//Open the file at the specified path and ensure file is opened properly.
FILE *tempFile = fopen(filePathName, "r");
if (!tempFile)
{
perror("\n\nError: Unable to open file for 'count_file_lines_characters'.\n");
exit(1);
}
int *fileCharCounts = allocate_memory_int_ptr(lineCount); //allocate memory to store the number of characters for each line.
// Initialize the array with zeros.
for (int i = 0; i < lineCount; i++)
{
fileCharCounts[i] = 0;
}
char *line = NULL;
size_t len = 0;
ssize_t read;
int currentLine = 0;
// Read each line from the file.
while ((read = getline(&line, &len, tempFile)) != -1 && currentLine < lineCount)
{
// If it's a line that needs to be skipped, just increment the line index.
if (currentLine < startLine)
{
currentLine++;
continue;
}
// Count characters in the line, excluding the newline character.
for (int i = 0; i < read; i++)
{
if (line[i] != '\n')
{
fileCharCounts[currentLine]++;
}
}
currentLine++;
}
free(line);
fclose(tempFile);
return fileCharCounts;
}
/**
* read_file_contents
*
* Reads the contents of a file into an array of strings.
* This function opens a file and reads its contents line by line, counting the characters in each line,
* and then reading each line into a dynamically allocated array of strings (char pointers).
* Each line is stored in the array up to the specified lineCount.
*
* @param filePathName A string representing the path of the file to be read.
* @param lineCount An integer specifying the number of lines to read from the file.
* @return A pointer to an array of strings, each string holding the content of a line.
*/
char** read_file_contents(const char* filePathName, int lineCount)
{
// Checking if the filePathName is NULL or if lineCount is less than or equal to 0.
// If so, return NULL as it's not possible to read the file contents under these conditions.
if (filePathName == NULL || lineCount <= 0)
{
perror("\n\nError:filePathName is NULL or if lineCount is less than or equal to 0 in 'read_file_contents'.");
return NULL;
}
//Open the file at the specified path and ensure file is opened properly.
FILE *tempFile = fopen(filePathName, "r");
if (!tempFile)
{
perror("\n\nError: Unable to open file for 'read_file_contents'.");
exit(1);
}
// First, count the characters in each line.
int *charCounts = count_file_lines_characters(filePathName, lineCount);
size_t maxLineLength = max_element_int(charCounts, lineCount);
// Allocate memory for the array of strings.
char **fileContents = allocate_memory_char_ptr_ptr(MAX_STRING_SIZE, lineCount);
size_t len = 0; // Buffer length for getline
size_t read; //
char *line = NULL;
int currentLine = 0;
// Read the file line by line and store each line in the corresponding string.
while ((read = getline(&line, &len, tempFile)) != -1 && currentLine < lineCount)
{
// Allocate memory for the current line in the array.
fileContents[currentLine] = allocate_memory_char_ptr((charCounts[currentLine] + 1));
// Copy the contents of the line into the allocated memory
strncpy(fileContents[currentLine], line, charCounts[currentLine]);
fileContents[currentLine][charCounts[currentLine]] = '\0'; // Null-terminate the string
currentLine++;
}
free(line);
free(charCounts);
fclose(tempFile);
return fileContents;
}
/**
* parse_file_contents
*
* Reads the contents of a file into an array of strings.
* This function opens a file and reads its contents line by line, counting the characters in each line,
* and then reading each line into a dynamically allocated array of strings (char pointers).
* Each line is stored in the array up to the specified lineCount.
*
* @param filePathName A string representing the path of the file to be read.
* @param lineCount An integer specifying the number of lines to read from the file.
* @return A pointer to an array of strings, each string holding the content of a line.
*/
char** parse_file_contents(const char* filePathName, int lineCount) // Conditionally reads the contents of a file into a string array
{
// Checking if the filePathName is NULL or if lineCount is less than or equal to 0.
// If so, return NULL as it's not possible to read the file contents under these conditions.
if (filePathName == NULL || lineCount <= 0)
{
perror("\n\nError:filePathName is NULL or if lineCount is less than or equal to 0 in 'parse_file_contents'.");
return NULL;
}
//Open the file at the specified path and ensure file is opened properly.
FILE *tempFile = fopen(filePathName, "r");
if (!tempFile)
{
perror("\n\nError: Unable to open file for 'parse_file_contents'.");
exit(1);
}
// First, count the characters in each line.
int *charCounts = count_file_lines_characters(filePathName, lineCount);
size_t maxLineLength = max_element_int(charCounts, lineCount);
// Allocate memory for the array of strings.
char **fileContents = allocate_memory_char_ptr_ptr(maxLineLength+1, lineCount);
size_t len = 0; // Buffer length for getline
size_t read; //
char *line = NULL;
int currentLine = 0;
// Read the file line by line and store each line in the corresponding string.
while ((read = getline(&line, &len, tempFile)) != -1 && currentLine < lineCount)
{
// Allocate memory for the current line in the array.
fileContents[currentLine] = allocate_memory_char_ptr((charCounts[currentLine] + 1));
// Copy the contents of the line into the allocated memory
strncpy(fileContents[currentLine], line, charCounts[currentLine]);
fileContents[currentLine][charCounts[currentLine]] = '\0'; // Null-terminate the string
currentLine++;
}
free(line);
free(charCounts);
fclose(tempFile);
// Replace double commas with a space to handle missing values.
// This is meant to ensure that empty fields are accounted for.
for (int i = 0; i < lineCount; i++)
{
char *tempData = fileContents[i];
int extraSpaceNeeded = 0;
// For each line, scan through the string and count how many times two commas appear consecutively. This will determine the additional space needed.
for (int j = 0; tempData[j] != '\0'; j++)
{
if (tempData[j] == ',' && tempData[j + 1] == ',')
{
extraSpaceNeeded += strlen(",0.0,") - 1; // Subtract 1 because we replace two commas.
}
}
// Allocate new memory for the modified string
char *modifiedData = allocate_memory_char_ptr(strlen(tempData) + extraSpaceNeeded + 1);
// Copy characters from the original string to the new string. When two consecutive commas are encountered, insert ", 0.0" and adjust the index accordingly.
for (int j = 0, k = 0; tempData[j] != '\0'; j++, k++)
{
if (tempData[j] == ',' && tempData[j + 1] == ',')
{
strcpy(&modifiedData[k], ",0.0,");
k += strlen(",0.0,") - 1; // Adjust index.
j++; // Skip the next comma in the original string.
}
else
{
modifiedData[k] = tempData[j];
}
}
modifiedData[strlen(tempData) + extraSpaceNeeded] = '\0'; // Null-terminate the new string.
// Replace the original string with the modified string.
free(fileContents[i]); // Free the memory allocated for the original string.
fileContents[i] = modifiedData;
}
return fileContents;
}
/**
* write_file_contents
*
* Writes an array of strings to a file.
* This function opens a file for writing and writes each string from
* the provided array (fileContents) to the file followed by a newline character.
* If writing fails, an error is reported and the program exits.
*
* @note The function assumes that the array is NULL-terminated, and that the individual
* strings do not contain newline characters at the end.
*
* @param filename A string representing the name of the file to write to.
* @param fileContents A pointer to an array of strings to be written.
*/
void write_file_contents(const char *filename, char **fileContents)
{
// Open the file for append and update
FILE *file = fopen(filename, "a+");
if (file == NULL)
{
perror("\n\nError opening file for writing in 'write_file_contents'.");
exit(1);
}
// Iterate through the array of strings
for (int i = 0; fileContents[i] != NULL; i++)
{
// Write each string to the file
if (fputs(fileContents[i], file) == EOF)
{
perror("\n\nError writing to file in 'write_file_contents'.");
fclose(file);
exit(1);
}
// Add a newline character to ensure the strings contain one
if (fputc('\n', file) == EOF)
{
perror("\n\nError writing to file in 'write_file_contents'.");
fclose(file);
exit(1);
}
}
fclose(file);
}
/**
* write_file_numeric_data
*
* Writes an array of double values to a file.
* This function opens a file in append mode and writes each double value from the provided
* data array to the file, each on a new line. The precision of the double values
* is maintained up to 17 significant digits. If writing fails, an error is reported
* and the program exits.
*
* @param filename A string representing the name of the file to write to.
* @param data A pointer to an array of double values.
* @param countDataEntries An integer specifying the number of entries in the data array.
*/
void write_file_numeric_data(const char *filename, double *data, int countDataEntries, const char *dataFieldName)
{
// Open the file for append and update
FILE *file = fopen(filename, "a+");
if (file == NULL)
{
perror("\n\nError opening file for writing in 'write_file_numeric_data'.");
exit(1);
}
/// Write the name of the data field to the file... the two lines of code below are analogous, although fprintf is primarily used for writing formatted data to a file, whereas fputs is more generally used to write string(s) to a file.
fprintf(file, "%s\n", dataFieldName);
//fputs(dataFieldName, file); //fputc('\n', file);
// Iterate through the array of strings
for (int i = 1; i < countDataEntries; i++)
{
// Write each data entry to the file
if (fprintf(file, "%.17g", data[i]) < 0)
{
perror("\n\nError writing to file in 'write_file_numeric_data'.");
fclose(file);
exit(1);
}
// Optionally add a newline character if the strings do not already contain one
if (fputc('\n', file) == EOF)
{
perror("\n\nError writing to file in 'write_file_numeric_data'.");
fclose(file);
exit(1);
}
// Unnecessary, keeping for reference.
//if(i == countDataEntries-1)
//{
//fputc('\n', file); //
//}
}
fclose(file);
}
/**
* load_data_from_file_as_double
*
* Load a column of numeric values from a text file into a freshly allocated
* double array, skipping the first line (assumed to be a header). Blank or
* whitespace-only lines are ignored. Lines that do not begin with a valid
* numeric token are also ignored.
*
* @param filePathName A string representing the name of the file to write to.
* @param outCount An integer pointer to store the number of data entries loaded.
* @return double* A pointer to an array of double values loaded from the file.
*/
double* load_data_from_file_as_double(const char *filePathName, int *outCount)
{
if (outCount) *outCount = 0;
int lineCount = count_file_lines(filePathName, MAX_NUM_FILE_LINES);
char **fileContents = read_file_contents(filePathName, lineCount);
if (!fileContents || lineCount <= 0) {
return NULL;
}
/* Assume first line is a header (e.g., "mass"); start reading at line 1. */
const int startIdx = 1;
/* -------- Pass 1: count valid numeric rows (skip blanks/whitespace) -------- */
int m = 0;
for (int i = startIdx; i < lineCount; ++i) {
const char *s = fileContents[i];
if (!s) continue;
/* Trim leading spaces/tabs only (keeps behavior consistent with prior code). */
while (*s == ' ' || *s == '\t') ++s;
if (*s == '\0') continue; /* blank line */
/* Check if a numeric token exists at the start of the (trimmed) line. */
char *endptr = NULL;
(void)strtod(s, &endptr);
if (endptr == s) continue; /* no numeric conversion at line start */
++m;
}
if (m <= 0) {
deallocate_memory_char_ptr_ptr(fileContents, lineCount);
return NULL;
}
/* -------- Pass 2: allocate and parse -------- */
double *data = allocate_memory_double_ptr(m);
int k = 0;
for (int i = startIdx; i < lineCount; ++i) {
char *s = fileContents[i];
if (!s) continue;
while (*s == ' ' || *s == '\t') ++s;
if (*s == '\0') continue;
char *endptr = NULL;
double v = strtod(s, &endptr);
if (endptr == s) continue; /* not numeric at the start */
data[k++] = v;
}
if (outCount) *outCount = k;
deallocate_memory_char_ptr_ptr(fileContents, lineCount);
return data;
}
/**
* generate_merged_filename
*
* Generates a merged filename based on two input file paths.
* The merged filename is constructed by combining the base names of the input files,
* appending "_merged" to the combined base names, and then prepending the directory path.
*
* @param filePath1 The path to the first file.
* @param filePath2 The path to the second file.
* @return A dynamically allocated string containing the new filename.
*/
char* generate_merged_filename(const char* filePath1, const char* filePath2)
{
// Extract the base names of the files, without extension or path, to avoid directory paths in the merged filename.
char* baseName1 = find_name_from_path(filePath1);
char* baseName2 = find_name_from_path(filePath2);
// Calculate the length needed for the new filename
size_t mergedLength = string_length(baseName1) + string_length(baseName2) + string_length("_merged") + 2; // +2 for underscore and null terminator
char* mergedFilename = allocate_memory_char_ptr(mergedLength);
if (mergedFilename == NULL)
{
perror("Memory allocation failed for merged filename");
return NULL;
}
sprintf(mergedFilename, "%s_%s_merged", baseName1, baseName2); // Construct the new filename
char *directoryPathName1 = find_file_directory_path(filePath1);
char *directoryPathName2 = find_file_directory_path(filePath2);
size_t characterCountMergedPathname = mergedLength;
characterCountMergedPathname += (directoryPathName1 == directoryPathName2) ? string_length(directoryPathName1) : maximum(string_length(directoryPathName1), string_length(directoryPathName2)); // If they are contained within the same enclosing directory, append the first directory pathname, otherwise, use the longer pathname.
char *mergedFilePathName = allocate_memory_char_ptr(characterCountMergedPathname); // Allocate memory for the merged file path name
sprintf(mergedFilePathName, "%s%s", directoryPathName1, mergedFilename); // Construct the full path name for the merged file
/// Cleanup memory
free(baseName1);
free(baseName2);
free(mergedFilename);
free(directoryPathName1);
free(directoryPathName2);
return mergedFilePathName; // Return the full path name of the merged file
}
/**
* merge_two_files
*
* This function merges the contents of two files into a new file.
* It reads the contents of the two input files, combines them, and writes the merged content to a new file.
* The new file's name is generated based on the names of the input files.
*
* @param filePath1 The path to the first file.
* @param filePath2 The path to the second file.
* @return The path to the merged file.
*/
char* merge_two_files(const char* filePath1, const char* filePath2)
{
// Count lines in each file
int lineCount1 = count_file_lines(filePath1, MAX_NUM_FILE_LINES);
int lineCount2 = count_file_lines(filePath2, MAX_NUM_FILE_LINES);
char** contents1 = read_file_contents(filePath1, lineCount1);
char** contents2 = read_file_contents(filePath2, lineCount2);
// Create filename based on input filenames, "merged" string literal, and enclosing directory of the files
char* mergedFilename = generate_merged_filename(filePath1, filePath2); // Combines the base names of the files(extracted from full path) then appends this to the path to the enclosing directory of the files
// Allocate memory for the merged contents array of strings
char** mergedContents = allocate_memory_char_ptr_ptr(MAX_STRING_SIZE, lineCount1 + lineCount2 + 1); // +1 for safety/null termination
// Copy contents from both files into the merged array
int i, j;
for (i = 0; i < lineCount1; i++)
{
mergedContents[i] = duplicate_string(contents1[i]); // Copy contents from the first file
}
for (j = 0; j < lineCount2; j++, i++)
{
mergedContents[i] = duplicate_string(contents2[j]); // Copy contents from the second file
}
mergedContents[i] = NULL; // Null-terminate the array
// Write the merged contents to the new file
write_file_contents(mergedFilename, mergedContents);
// Cleanup memory
deallocate_memory_char_ptr_ptr(contents1, lineCount1);
deallocate_memory_char_ptr_ptr(contents2, lineCount2);
deallocate_memory_char_ptr_ptr(mergedContents, lineCount1 + lineCount2);
return mergedFilename; // Return the path to the merged file
}