#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char ramSlowFwdIndex[4];
char ramSlowBwdIndex[4];
char rammingShellFwdIndex[4];
char rammingShellBwdIndex[4];
char breechOpenIndex[4];
char breechCloseIndex[4];
char encoderDataIndex[4];
} fileIndexType;
void incrementIndex(char *index, int incrementValue);
void readAndUpdateFileIndex(const char *fileName, fileIndexType *fileIndex, int incrementValue, const char *variable);
int main() {
FILE *file = fopen("example.txt", "w+");
if (file == NULL) {
printf("Error: Unable to open file for reading\n");
return 1;
}
fclose(file);
fileIndexType fileIndex = {"001", "001", "001", "001", "001", "001", "001"};
readAndUpdateFileIndex("example.txt", &fileIndex, 1, "rammingShellBwdIndex"); // Increment 'rammingShellBwdIndex' value by 1
return 0;
}
void incrementIndex(char *index, int incrementValue) {
int value = atoi(index) + incrementValue;
sprintf(index, "%03d", value);
}
void readAndUpdateFileIndex(const char *fileName, fileIndexType *fileIndex, int incrementValue, const char *variable) {
FILE *file = fopen(fileName, "r+");
if (file == NULL) {
printf("Error: Unable to open file for reading\n");
return 1;
}
fscanf(file, "%s %s %s %s %s %s %s", fileIndex->ramSlowFwdIndex, fileIndex->ramSlowBwdIndex,
fileIndex->rammingShellFwdIndex, fileIndex->rammingShellBwdIndex,
fileIndex->breechOpenIndex, fileIndex->breechCloseIndex, fileIndex->encoderDataIndex);
fclose(file);
// Increment the desired variable
if (strcmp(variable, "ramSlowFwdIndex") == 0) {
incrementIndex(fileIndex->ramSlowFwdIndex, incrementValue);
} else if (strcmp(variable, "ramSlowBwdIndex") == 0) {
incrementIndex(fileIndex->ramSlowBwdIndex, incrementValue);
} else if (strcmp(variable, "rammingShellFwdIndex") == 0) {
incrementIndex(fileIndex->rammingShellFwdIndex, incrementValue);
} else if (strcmp(variable, "rammingShellBwdIndex") == 0) {
incrementIndex(fileIndex->rammingShellBwdIndex, incrementValue);
} else if (strcmp(variable, "breechOpenIndex") == 0) {
incrementIndex(fileIndex->breechOpenIndex, incrementValue);
} else if (strcmp(variable, "breechCloseIndex") == 0) {
incrementIndex(fileIndex->breechCloseIndex, incrementValue);
} else if (strcmp(variable, "encoderDataIndex") == 0) {
incrementIndex(fileIndex->encoderDataIndex, incrementValue);
} else {
printf("Error: Invalid variable specified\n");
return 1;
}
// Write updated value back to file
file = fopen(fileName, "w");
if (file == NULL) {
printf("Error: Unable to open file for writing\n");
return 1;
}
fprintf(file, "%s %s %s %s %s %s %s", fileIndex->ramSlowFwdIndex, fileIndex->ramSlowBwdIndex,
fileIndex->rammingShellFwdIndex, fileIndex->rammingShellBwdIndex,
fileIndex->breechOpenIndex, fileIndex->breechCloseIndex, fileIndex->encoderDataIndex);
fclose(file);
}
Saturday, 16 March 2024
Code for updating a structure
Subscribe to:
Comments (Atom)