Config / .cfg / .ini file linked with c program - c

I made program that helps with learning english. You have code below, but for my question you don't need to read and understand what's inside. What I want to do is to create .cfg or .ini file, that can be open with simple notepad and lets user modify:
MAX size (default is 15)
Sleep(x) value (default is 500)
I have no idea how can I make such config file that can be modified by user,link it with my c code, and then after runing program.exe it accepts changes from there. Any ideas?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <Windows.h>
#define MAX 15 //word max size
struct slowa
{
char pl_word[MAX];
char eng_word[MAX];
};
void menu(void);
int count_lines(FILE*);
void print_array1 (const int[],int); //print 1-dimension array
void swap (int*,int*);
int main ()
{
srand( time( NULL ) );
int i,k,j;
FILE* fp;
fp = fopen ("tekst", "r");
if (!fp)
{
printf ("zjebales"); //"you fucked up"
return -1;
}
const int lines = count_lines(fp);
int tab[lines]= {};
int* temp = (int*)malloc(lines*sizeof(int));
for (j=0; j<lines; j++)
{
temp[j]=j+1;
}
j=lines;
for (i=0; i<lines; i++)
{
k=rand()%j--;
tab[i]=temp[k]-1;
swap(temp+k,temp+j);
}
free(temp);
struct slowa arr[lines];
rewind (fp);
for (i=0; i<lines; i++)
{
fscanf(fp, "%s %s", arr[tab[i]].pl_word, arr[tab[i]].eng_word);
}
fclose(fp);
char text[MAX];
k=0;
system("cls");
menu();
scanf("%d",&j);
system("cls");
char ch;
while ((ch = getchar()) != '\n' && ch != EOF);
switch (j)
{
case 1:
for (i=0; i<lines; i++)
{
printf ("Podaj tlumaczenie:%s\n", arr[i].eng_word); //"Write translation"
//fgets (text, MAX, stdin);
scanf ("%s",text);
if (strcmp(arr[i].pl_word, text) == 0)
{
puts ("DOBRZE!"); //"Correct!"
k++;
}
else puts ("ZLE!"); //"Wrong"
Sleep(500);
system("cls");
}
break;
case 2:
for (i=0; i<lines; i++)
{
printf ("Podaj tlumaczenie:%s\n", arr[i].pl_word); //"Write translation"
scanf ("%s",text);
if (strcmp(arr[i].eng_word, text) == 0)
{
puts ("DOBRZE!"); //Correct!
k++;
}
else puts ("ZLE!"); //Wrong!
Sleep(500);
system("cls");
}
break;
default:
puts ("miales podac 1 lub 2 dzbanie"); //"You should put 1 or 2"
getchar();
return -1;
}
printf ("Odpowiedziales dobrze na %d/%d pytan. ", k, lines); //"You answered correctly k/lines words"
if (k==lines) puts("No dobra cos tam umiesz");
else if(k>(lines/2)&&k<lines) puts ("Mogloby byc lepiej");
else puts ("Wracaj do nauki debilu");
while ((ch = getchar()) != '\n' && ch != EOF);
getchar();
return 0;
}

Related

Recursive inverting

i made this code for my college lesson:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
int palindromoR(int i, int f, char *s)
{
if (f - i <= 0)
return 1;
if (s[i] != s[f]) {
return 0;
} else {
return palindromoR(i+1, f-1, s);
}
}
void palindromo(char *s)
{
int saida = palindromoR(0, strlen(s) - 1, s);
if (saida)
{
printf("eh palindromo\n");
}
else
{
printf("nao eh palindromo\n");
}
}
void inversaR(char *str)
{
static int i=0;
int tam = strlen(str) - i;
char temp;
if (tam +1 == 0)
return;
temp = str[tam];
printf ("%c",temp);
i++;
return inversaR (str);
}
void inversa(char *s)
{
inversaR(s);
printf("\n");
}
unsigned long stirlingR(unsigned long n, unsigned long k)
{
// implemente essa função recursiva
return 0;
}
void stirling(int n, int k)
{
printf("%lu\n", stirlingR(n, k));
}
void padraoR(unsigned n)
{
}
void padrao(unsigned n)
{
padraoR(n);
printf("\n");
}
int main(int argc, char *argv[])
{
char file_name[MAX], aux[MAX];
FILE *entrada;
int t, a, b;
scanf("%s", file_name);
entrada = fopen(file_name, "r");
if (entrada == NULL)
{
printf("Nao encontrei o arquivo!");
exit(EXIT_FAILURE);
}
fscanf(entrada, "%d", &t);
if (t < 1 || t > 4)
{
printf("Parametros incorretos.\n");
printf("Ex:\n");
printf("tp01_recursao 1 [para testar palindromo]\n");
printf("tp01_recursao 2 [para testar inversa]\n");
printf("tp01_recursao 3 [para testar Stirling]\n");
printf("tp01_recursao 4 [para testar padrao]\n");
}
if (t == 1)
{
printf("\nTestando palindromo()\n\n");
fscanf(entrada, "%s", aux);
while (aux[0] != '.')
{
palindromo(aux);
fscanf(entrada, "%s", aux);
}
}
else if (t == 2)
{
printf("\nTestando inversa()\n\n");
fscanf(entrada, "%s", aux);
while (aux[0] != '.')
{
inversa(aux);
fscanf(entrada, "%s", aux);
}
}
else if (t == 3)
{
printf("\nTestando Stirling()\n\n");
fscanf(entrada, "%d %d", &a, &b);
while (a != -1)
{
stirling(a, b);
fscanf(entrada, "%d %d", &a, &b);
}
}
else if (t == 4)
{
printf("\nTestando padrao()\n\n");
fscanf(entrada, "%d", &a);
while (a != -1)
{
padrao(a);
fscanf(entrada, "%d", &a);
}
}
return 0;
}
My function inversaR seems to work when i try like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void inversaR(char *str)
{
static int i=0;
int tam = strlen(str) - i;
char temp;
if (tam +1 == 0)
return;
temp = str[tam];
printf ("%c",temp);
i++;
return inversaR (str);
}
void inversa(char *s)
{
inversaR(s);
printf("\n");
}
int main (){
char teste[100] = "alucard";
inversa(teste);
return 0;
}
the code above gives me the answer "dracula" as expected, but when trying with the first code it cuts the strings in 2 characters. The archive it's reading contains the following strings:
2
ab
gato
minerva
alucard
.
I tried to chance it using the function strrev() and it seems to work just fine, otherwise the same problem kept blowing my mind.
I tried out your code and saw the quirky chopped output you referred to. Doing some debugging of the code led me to the issue with your static variable, "i" in the recursive "inversaR" function. After each call with a different string, the value was left with an arbitrary value from the previous recursive call set which was giving either a partial string or no string at all.
With that it was apparent that when the final character had been printed and the return back up the function call stack was occurring, this variable needed to be reset. Following is a refactored version of the function.
void inversaR(char *str)
{
static int i=0;
int tam = strlen(str) - i;
char temp;
//printf("tam: %d\n", tam);
if (tam +1 == 0)
{
i = 0; /* This needs to be reset when returning up the recursive call stack */
return;
}
temp = str[tam];
printf ("%c",temp);
i++;
return inversaR (str);
}
Also, just to clarify to anyone testing this program, I added a "printf" statement prior to the prompt for a file name so that it is clear what is wanted for input.
printf("File name: "); /* Added to alert the user to enter a file name */
scanf("%s", file_name);
entrada = fopen(file_name, "r");
With those two bits of code refactored, and having created a text file with the sample string set, the following terminal output was created.
#Vera:~/C_Programs/Console/Dracula/bin/Release$ ./Dracula
File name: Test.txt
Testando inversa()
ba
otag
avrenim
dracula
All of the strings appear to have been properly reversed. Go ahead and try out these program tweaks and see if they meet the spirit of your project.

Not Getting Output in File

#include <stdio.h>
int main()
{
FILE *f1;
int ch, i, n = 0;
char q[500], opt[4][100];
int corAns;
f1 = fopen("C://Users//Lenovo//Desktop//fileInC1.txt", "a+");
if (f1 == NULL)
{
printf("Error Opening File.");
return 0;
}
else
{
while (n != 2)
{
n++;
printf("\nQuestion: ");
fgets(q, 500, stdin);
for (i = 0; i < 4; i++)
{
printf("\nOption %d: ", i + 1);
fgets(opt[i], 100, stdin);
}
printf("\nCorrect answer: ");
scanf("%d", corAns);
//program terminating here after only one iteration
fprintf(f1, "{\nQ: \"%s\", \n\topt: [\"%s\", \"%s\", \"%s\", \"%s\"], \n\tCA: %d }", q, opt[0], opt[1], opt[2], opt[3], corAns);
printf("\nData Written Successfully.");
}
}
fclose(f1);
return 0;
}
I have been trying to create a Javascript generator as you can see in the code.
The main problem i am getting is inside the while loop.
The while loop is terminating after only one iteration and the program not writting the data in the created file. The file already exists.
I am not getting where is the problem occuring.
You need to cleanse your input of new-lines. You also had a redundant Else statement, and Scanf requires the address of a variable, not it's value.
This should work for you. You can check out this question here: Fgets skipping inputs, which I shamelessly copied.
#include <stdio.h>
#include <string.h>
int main()
{
FILE *f1;
int ch, i, n = 0;
char q[500], opt[4][100];
int corAns;
int c;
char *p;
f1 = fopen("fileInC1.txt", "a+");
if (f1 == NULL)
{
printf("Error Opening File.");
return 0;
}
while (n != 2)
{
n++;
printf("\nQuestion: ");
fgets(q, 500, stdin);
if ((p=strchr(q, '\n')) != NULL) *p = '\0';
for (i = 0; i < 4; i++)
{
printf("\nOption %d: ", i + 1);
fgets(opt[i], 100, stdin);
if ((p=strchr(opt[i], '\n')) != NULL) *p = '\0';
}
printf("\nCorrect answer: ");
scanf("%d", &corAns);
//program terminating here after only one iteration
fprintf(f1, "{\nQ: \"%s\", \n\topt: [\"%s\", \"%s\", \"%s\", \"%s\"], \n\tCA: %d }", q, opt[0], opt[1], opt[2], opt[3], corAns);
printf("\nData Written Successfully.");
while ( (c = getchar()) != '\n' && c != EOF );
}
fclose(f1);
return 0;
}

Printing 2d Array with unknown number of strings in C

I have written a small program to read in a series of strings from a file and then to store them in a 2D Arrray. The strings are read into the array correctly, yet my program is not countering the number of rows in the file like I had expected.
I am honestly at a loss and cannot figure out why the program is not counting the rows in the file. Any explanation as to what I am doing wrong is greatly appreciated.
Here is the code that I have so far:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE* fp;
char nameArray[20][120], str[20];
int i = 0, j = 0, n;
int count = 0;
char name[20]; //filename
int ch;
printf("Please enter a file name: ");
scanf("%s", &name);
fp = fopen(name, "r");
if (fp == NULL) {
printf("File \"%s\" does not exist!\n", name);
return -1;
}
while (fscanf(fp, "%s", str) != EOF)
{
strcpy(nameArray[i], str);
i++;
}
while ((ch = fgetc(fp)) != EOF) {
if (ch == '\n')
count++;
}
for (i = 0; i<=count; i++)
{
printf("%s", nameArray[i]);
}
fclose(fp);
return 0;
}

Trouble with C program that reads a MIPS instructions, outputs file with line number, and summary

The problem: Use a c program to read a MIPS instruction file, output it to a second file (both are command line arguments) which contains the contents of the MIPS file, with line numbers. The second half is supposed to display a cross reference table, which details the identifier, the definition(a number), and the usage of that identifier, by line number, for any identifier used more than once.
Unfortunately, I've run aground, and the program not only doesnt seem to actually print anything, but it doesnt seem to make any files either. This is a bit of a last ditch effort, to see if anyone else can help me out.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*Func line takes in a file, and places a line number at the beginning of every
non blank line */
void line(FILE *input, FILE *output) {
char a, c;
int lineNum = 0;
int startOfLine = 1;
char ch;
fprintf(output, "%d ", ++lineNum);
//copy the contents of the input file into the output file
do {
a = fgetc(input);
fputc(a, output);
c = getc(input);
if(a == '\n' && c != '\n') {
if(lineNum > 9)
fprintf(output, "%d ", ++lineNum);
else
fprintf(output, "%d ", ++lineNum);
}
ungetc(c, input);
} while (a != EOF);
printf("ran line: \n");
}
/* Func cross takes in a file, and finds each identifier, marks its definition, and every
use and returns that in the output file */
void cross(FILE *input, FILE *output) {
FILE *temp = fopen("temp.txt", "a+");
int lineNum = 0;
int startOfLine = 1;
char identifier[20][10];
char a, c, i;
int j, k, p;
int size=0;
int def[20];
int use[20][50];
char tempstr[80];
fprintf(output, "Identifier\tDefinition\t Use\n");
fprintf(temp, "%d ", ++lineNum);
//copy contents of input into a temp file
do {
a = fgetc(input);
fputc(a, temp);
c = getc(input);
if(a == '\n' && c != '\n') {
if(lineNum > 9)
fprintf(temp, "%d ", ++lineNum);
else
fprintf(temp, "%d ", ++lineNum);
}
ungetc(c, input);
} while (a != EOF);
fclose(temp);
fopen("temp.txt", "r");
j=0;
//checks to see if current line has an Identifier and if so saves it to an array
//along with the line number it was defined on
while(fgets(tempstr, 80, temp)) {
if(isalpha(tempstr[4]) || tempstr[4] == '_') {
sscanf(tempstr, "%d %[0-9_A-Z_a-z_]", &def[j], identifier[j]);
j++;
size++;
}
}
fclose(temp);
fopen("temp.txt", "r");
//checks for each identifier, on every line whether or not that identifier is used
while(fgets(tempstr, 80, temp)) {
char *tempNum;
sscanf(tempstr, "%s", tempNum);
int tempN = atoi(tempNum);
int n;
p=0;
for(n=0; n<size; n++) {
if(strstr(tempstr, identifier[n]) && tempN > def[n] && tempstr[4] != '#') {
use[n][p] = tempN;
p++;
}
}
}
//writes the identifier, definition, and uses to the file
for(k=0;k<size;k++) {
fprintf(output, "%s\t\t %d\t\t ", identifier[k], def[k]);
for(p=0; p<50; p++) {
if(use[k][p] != NULL && use[k][p] < lineNum && use[k][p] > def[k])
fprintf(output,"%d ", use[k][p]);
}
fprintf(output, "\n");
}
printf("ran cross: \n");
}
/*Func both returns the file with numbered lines and a cross reference table at the bottom of the file */
void both(FILE *input, FILE *output, char *outputName) {
FILE *lineFile = fopen("line.txt", "a+");
FILE *crossFile = fopen("cross.txt", "a+");
char ch;
line(input, lineFile);
cross(input, crossFile);
while( (ch = fgetc(lineFile)) != EOF)
fputc(ch, output);
fprintf(output, "\n\t\t\tCross Reference Table\n");
while( (ch = fgetc(crossFile)) != EOF)
fputc(ch, output);
fclose(output);
printf("ran both: \n");
}
int main(int argc, char * argv[]) {
FILE *input, *output;
output = fopen(argv[4], "a+");
char outputName[50];
strcpy(outputName, argv[4]);
//Error testing
if(argc > 5)
exit(1);
if(strcmp(argv[2], "-l") != 0 && strcmp(argv[2], "-c") != 0 && strcmp(argv[2], "-b") != 0) {
printf("Incorrect flag syntax... Exiting\n");
exit(1);
}
if((input = fopen(argv[3], "r+")) == NULL) {
printf("Input file could not be opened... Exiting\n");
exit(1);
}
else {
if(strcmp(argv[2], "-l") == 0) {
line(input, output);
}
else if(strcmp(argv[2], "-c") == 0)
cross(input, output);
else {
both(input, output, outputName);
}
}
printf("ran main: \n");
return 0;
}

Frequency of specific symbols on each line of a text file

I am making a C program that counts the occurrence of the symbol ; and . and display their frequency for each line of a text file.
My code only works with only one symbol counter for dotcoma (counts ;) and when I add another counter varriable coma(counts .) it gives me an error.
Stack arround varriable was corrupted.
Here is the full code:
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS /* Да си изключа предупрежденията*/
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>/* For exit() function */
int main()
{
char file_name[1000];
FILE *file2 = 0;
gets(file_name);
int rows = 1;//broq na vsichki redove
int dotcoma[150];//broq na ;
int coma[150];//broq na .
int j;
char c;
file2 = fopen(file_name, "r");//otvarq faial za chetene
if (file2 == NULL){
printf("Cannot open %s\n", file_name);
exit(2);
}//if
for (j = 0; j<150; j++)
dotcoma[j] = 0;
coma[j] = 0;
do{
c = fgetc(file2);
if (c == '\n') rows++;
else{
if (c == ';')
dotcoma[rows - 1]++;
if (c == '.')
coma[rows-1]++;
}
} while (c != EOF);//chete do kraq na faila
if (ferror(file2)){
printf("Error reading file.\n");
exit(2);
}//if
printf("The number of the symbols on a row ");
for (j = 0; j<rows; j++){
printf("Row %d: %f %f\n", j + 1, (float)dotcoma[j], (float)coma[j]);
}
_getche();
if (fclose(file2) == EOF){
printf("Cannot close %s\n", file_name);
exit(2);
_getche();
return 0;
}
}
Try to fix your coma initialization! You forgot the brackets!
for (j = 0; j<150; j++){
dotcoma[j] = 0;
coma[j] = 0;
}
Here it is.
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS /* Да си изключа предупрежденията*/
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>/* For exit() function */
int main()
{
char file_name[1000];
FILE *file2 = 0;
gets(file_name);
int rows = 1;//broq na vsichki redove
int dotcoma[150];//broq na ;
int coma[150];//broq na .
int j;
char c;
file2 = fopen(file_name, "r");//otvarq faial za chetene
if (file2 == NULL){
printf("Cannot open %s\n", file_name);
exit(2);
}//if
for (j = 0; j<150; j++)
{
dotcoma[j] = 0;
coma[j] = 0;
}
do{
c = fgetc(file2);
if (c == '\n') rows++;
else{
if (c == ';')
dotcoma[rows - 1]++;
if (c == '.')
coma[rows-1]++;
}
} while (c != EOF);//chete do kraq na faila
if (ferror(file2)){
printf("Error reading file.\n");
exit(2);
}//if
printf("The number of the symbols on a row ");
for (j = 0; j<rows; j++){
printf("Row %d: %f %f\n", j + 1, (float)dotcoma[j], (float)coma[j]);
}
_getche();
if (fclose(file2) == EOF){
printf("Cannot close %s\n", file_name);
exit(2);
_getche();
return 0;
the return statement is inside the if(fclose...) this means the compiler will raise a warning about missing return statement
the initialization of dotcoma and coma arrays is failing becuase the 'if' only handles one code block and the coma[j] =0; is not inside a code block, This is another good reason to ALWAYS place { and } around every code block
under DOS/Windows, a new line is two characters, so this line: if (c == '\n') shows that 'c' should be an int, not a char
regarding this line: FILE *file2 = 0; file2 is a pointer, not an integer, so the line should be: FILE *file2 = NULL;
to avoid edit problems and simplify future maintenance, the 'magic number' 150 should be defined as '#define MAX_COUNT (150)' then MAX_COUNT should be used in all cases rather than the literal 150
Similar considerations should be applied for file_name
the function: getchar() returns a int value (so EOF can be recognized) so this line: 'char c;' should be 'int c;'
the exit() prototype is in stdlib.h not conio.h
regarding this line: gets(file_name); gets() is full of security problems and many other problems. It is depreciated from the C language. Much better to use fgets() as, amongst other things, it limits the number of characters read, so input buffer overflow does not occur.
#include <stdio.h>
#include <stdlib.h> /* For exit() function */
#include <string.h>
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS /* Да си изключа предупрежденията*/
#include <conio.h>
#endif
#define MAX_ROWS (150)
#define MAX_FILENAME_LEN (1000)
int main()
{
char file_name[MAX_FILENAME_LEN];
FILE *file2 = NULL;
if( NULL == fgets(file_name, MAX_ROWS, stdin)
{
perror( "fgets failed" );
exit( EXIT_FAILURE )
}
// implied else, fgets successful
int rows = 1;//broq na vsichki redove
int dotcoma[MAX_ROWS] = {0};//broq na ;
int coma[MAX_ROWS] = {0};//broq na .
int j; // index/loop counter
int c; // char input from console
if( NULL == (file2 = fopen(file_name, "r") )//otvarq faial za chetene
{
perror( "fopen failed for input file" );
exit(2);
}//if
// implied else, fopen successful
while( EOF != (c = fgetc(file2) )
{
switch( c )
{
case '\n':
rows++;
break;
case ';':
dotcoma[rows - 1]++;
break;
case '.':
coma[rows-1]++;
break;
default: // all other characters
break;
} // end switch
} // end while
printf("The number of the symbols on a row ");
for (j = 0; j<rows; j++)
{
printf("Row %d: %f %f\n", j + 1, (float)dotcoma[j], (float)coma[j]);
}
fclose( file2 );
getchar(); // wait for user to read screen and enter a char
return 0;
} // end function: main

Resources