I need to make global variables used in many functions local one - c

So I,ve written a program which counts for,while,do/while and emty lines. Can anyone help me make FILE *fin and FILE *fout local variables. It turned out that i cant use global ones and now I am stuck. Here is the code:
#include <stdio.h>
#include <string.h>
FILE *fin;
FILE *fout;
void stats();
void open_file1();
void open_file2();
int main()
{
char menu = 0;
printf("1.Read from file and write stats to another\n\n");
printf("2.Read from file and write stats to screen\n\n");
printf("3.Read from keyboard and write to file\n\n");
printf("4.Read from keyboard and write to display\n\n");
printf("5.Exit\n\n");
do
{
printf("Choose an option from 1-5: ");
fflush(stdin);
scanf("%c", &menu);
printf("\n");
switch (menu)
{
case '1':
open_file1();
open_file2();
stats(fin, fout);
fclose(fin);
fclose(fout);
break;
case '2':
open_file1();
stats(fin, stdout);
fclose(fin);
break;
case '3':
open_file2();
printf("Enter text:\n");
stats(stdin, fout);
fclose(fout);
break;
case '4':
printf("Enter text\n");
stats(stdin, stdout);
break;
default:
if (menu != '5')
printf("Invalid.");
break;
}
} while (menu != '5');
return 0;
}
void stats(FILE *fin, FILE *fout)
{
char string[1000];
int count = 0, fcount = 0, wcount = 0, dcount = 0, empty = 0;
while (fgets(string, 10000, fin) != NULL)
{
unsigned int i;
for (i = 0; i < strlen(string); i++)
{
if ((string[i] == '"'))
{
while (string[i += 1] != '"')
continue;
}
if ((string[i] == '/') && (string[i + 1] == '*'))
{
while (string[i += 1])
continue;
}
if ((string[i] == '/') && (string[i + 1] == '/'))
{
while (string[i += 1] != '\n')
continue;
}
if (string[i] == 'f' && string[i + 1] == 'o'&& string[i + 2] == 'r'&& string[i + 3] != '*') fcount++;
if (string[i] == 'w' && string[i + 1] == 'h' && string[i + 2] == 'i' && string[i + 3] == 'l'&& string[i + 4] == 'e'&& string[i + 5] != '*') wcount++;
if (string[i] == 'd' && string[i + 1] == 'o'&& string[i + 2] != '*') dcount++;
}
for (i = 0; i < strlen(string); i++)
{
if (string[i] != ' ' && string[i] != '\n'&& string[i] != '\t')
{
count = 0;
break;
}
count = 1;
}
if (count == 1)
empty++;
}
fprintf(fout, " for %d ,while %d и do/while %d\n", fcount, wcount = wcount - dcount, dcount);
fprintf(fout, "The number of emtpy line is: %d\n", empty);
}
void open_file1()
{
char file1[100];
while (file1[strlen(file1) - 1] != 'c'&&file1[strlen(file1) - 2] != '.')
{
printf("Please enter file to read from. Мust be C file: ");
scanf("%s", file1);
}
fin = fopen(file1, "r");
if (fin == NULL)
{
printf("There is no such file or directory\n");
open_file1();
}
}
void open_file2()
{
char file2[100];
printf("Enter file to write in: ");
scanf("%s", file2);
fout = fopen(file2, "w");
if (fout == NULL)
{
printf("There is no such file or directory\n");
open_file2();
}
}

Change
void open_file1();
void open_file2();
to open the files and return the corresponding FILE*.
FILE* open_file1();
FILE* open_file2();
Then, change their implementation to:
FILE* open_file1()
{
FILE* fin = NULL;
char file1[100];
while (file1[strlen(file1) - 1] != 'c'&&file1[strlen(file1) - 2] != '.')
{
printf("Please enter file to read from. ?ust be C file: ");
scanf("%s", file1);
}
fin = fopen(file1, "r");
if (fin == NULL)
{
printf("There is no such file or directory\n");
}
return fin;
}
Make similar changes to open_file2.
Then, change the way they are used.
Instead of
open_file1();
open_file2();
use
fin = open_file1();
fout = open_file2();
Make sure to:
declare fin and fout at the top of main.
pass them to the functoins that access the global variables.

CHeck the code below
FILE *open_file1();
int main()
{
FILE *fin=NULL;
FILE *fout=NULL;
fin = open_file1();
// Rest of your code
return 0;
}
FILE *open_file1()
{
FILE *fp=NULL;
// open the file and
return fp;
}

Related

Why is my string changing contents after leaving the for loop it is contained in

I'm trying to create a program that takes in command line arguments to take in text and output it into another text file swapping out characters and replacing them with a different one based upon user input, but when I try to open the input file it is unable to open because the contents of the string changes after leaving the for loop. I did initialize the string before hand and later assigned the name of the input file from the command line and once the initial for loop
Command terminal:
./a.out --hi -+yo -i input.txt -o output.txt
Letters to replace with:
h
i
String(2): h i
from[2]
Letters to be replaced:
y
o
String(2): y o
input File Name:
i
String(1): i
n
String(2): i n
p
String(3): i n p
u
String(4): i n p u
t
String(5): i n p u t
.
String(6): i n p u t .
t
String(7): i n p u t . t
x
String(14): i n p u t . t x � , � p � U
t
String(14): i n p u t . t x t , � p � U
String(9): i n p u t . t x t
String(9): i n p u t . t x t
String(9): i n p u t . t x t
String(6): 0 � � � �
End of Program
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void help()
{
printf("HELP TEXT\n\n");
}
void printString(char *string)
{
//String Test
printf("String(%ld): ", strlen(string));
int p = 0;
for (p = 0; p < strlen(string); p++)
{
printf("%c ", string[p]);
}
printf("\n");
}
int main(int argc, char *argv[])
{
int i, toLen, fromLen;
int fromChars = 0, toChars = 0, outArg = 0, inpArg = 0;
char *to;
char *from;
FILE *fileInput;
FILE *fileOutput;
char c;
for (i = 0; i < argc; i++)
{
//Begin argument search
int j;
//printf("argv[%d]: %s\n", i, argv[i]);//Curren Argv
for (j = 0; j < strlen(argv[i]); j++)
{
//Loop each arg starting with '-'
//printf("char: %c\n", argv[i][j]);//Char of Argv[#]
if (argv[i][j] == '-')
{
if (argv[i][j + 1] == 'h')
{
//help trigger
printf("Help Prompt\n");
help();
return 0;
}
if ((argv[i][j + 1] == '-') && (fromChars != 1))
{
//letters to replace trigger
printf("Letters to replace with:\n");
int k;
char fromCharString[strlen(argv[i])];
for (k = 2; k <= strlen(argv[i]); k++)
{
//Moves from current pos char to a separate string
printf("%c\n", argv[i][k]);
fromCharString[k - 2] = argv[i][k];
}
from = fromCharString;
printString(from);
fromLen = strlen(from);
printf("from[%ld]\n", strlen(from));
if (dupeCheck(fromCharString) == 1)
{
//Checks for duplicate letters
return 1;
}
fromChars = 1; //Flag use of fromChars
j = strlen(argv[i]); //Moves to next argument
}
else if ((argv[i][j + 1] == '-') && (fromChars == 1))
{
printf("sub: ERROR - multiple \"--\" arguments detected\n");
return 1;
}
if ((argv[i][j + 1] == '+') && (toChars != 1))
{
//letters to replace trigger
printf("Letters to be replaced:\n");
int k;
char toCharString[strlen(argv[i])];
for (k = 2; k <= strlen(argv[i]); k++)
{
printf("%c\n", argv[i][k]);
toCharString[k - 2] = argv[i][k];
}
to = toCharString;
printString(to);
toLen = strlen(to);
toChars = 1;
j = strlen(argv[i]);
}
else if ((argv[i][j + 1] == '+') && (toChars == 1))
{
printf("sub: ERROR - multiple \"-+\" arguments detected\n");
return 1;
}
if ((argv[i][j + 1] == 'o') && (outArg != 1))
{
i++;
//output file
//printf("Output File Name:\n");
int k;
char outputName[strlen(argv[i])];
for (k = 0; k <= strlen(argv[i]); k++)
{
//printf("%c \n", argv[i][k]);
outputName[k] = argv[i][k];
//printString(outputName);
}
//printString(outputName);
printf("\n");
fileOutput = fopen(outputName, "w");
fclose(fileOutput);
if(fileOutput == NULL)
{
printf("sub: ERROR - output file \"%s\" could not be created\n",outputName);
return 1;
}
outArg = 1;
j = strlen(argv[i]);
}
else if ((argv[i][j + 1] == 'o') && (toChars == 1))
{
printf("sub: ERROR - multiple output file arguments \n");
return 1;
}
if (((argv[i][j + 1] == 'i') && (outArg != 1)))
{
i++;
//input file
printf("input File Name:\n");
int k;
char inputName[strlen(argv[i])];
for (k = 0; k <= strlen(argv[i]); k++)
{
printf("%c \n", argv[i][k]);
inputName[k] = argv[i][k];
printString(inputName);
}
printString(inputName);
printf("\n");
to = inputName;
printString(to);
fileInput = fopen(inputName, "r");
fclose(fileInput);
if(fileInput == NULL)
{
printf("sub: ERROR - invalid input file not found\n");
return 1;
}
inpArg = 1;
j = strlen(argv[i]);
}
}
}
if (fromChars == 1 && toChars == 1)
{
//printf("from length:%d \nto length:%d\n", fromLen, toLen);
if (fromLen > toLen)
{
printf("sub: ERROR - missing replacement character\n");
return 1;
}
else if (fromLen < toLen)
{
printf("sub: WARNING - extraneous replacement character \n");
}
}
if (outArg == 0)
{
//check if ther is an output name
fileOutput = fopen("output.txt", "w");
}
}
printString(to);
printf("\nEnd of Program\n");
return 0;
}
It was difficult for me to read through the code. I tried to re-structure the code a bit using enum and switch-case and tried to eliminate some for loops by using inbuilt functions like memset and memcpy (you can also use strncpy instead). I think the arguments parsing works and I hope I have considered most of the scenarios.
Hope this helps a bit.
NOTE:
I haven't completed the code, many parts are remaining which are marked as TODO in the comments.
There was an Undefined reference to a function dupeCheck() in your code.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void help()
{
printf("HELP TEXT\n\n");
}
void printString(char *s)
{
printf("String: %s [%d]\n", s, strlen(s));
}
enum TokenType
{
INPUT_FILE,
OUTPUT_FILE,
CHARS_TO_REPLACE_WITH,
CHARS_TO_BE_REPLACED,
HELP,
OPTION_VALUE,
INVALID
};
// returns the type of token
enum TokenType getTokenType(const char* token)
{
if (token == NULL)
return INVALID;
const int len = strlen(token);
if (len >= 2)
{
switch (token[0])
{
// options
case '-':
{
switch (token[1])
{
case 'h':
if (len > 2)
return INVALID;
return HELP;
case '-':
if (len <= 2)
return INVALID;
return CHARS_TO_REPLACE_WITH;
case '+':
if (len <= 2)
return INVALID;
return CHARS_TO_BE_REPLACED;
case 'i':
if (len > 2)
return INVALID;
return INPUT_FILE;
case 'o':
if (len > 2)
return INVALID;
return OUTPUT_FILE;
default:
printf("Something went wrong: invalid token %s\n", token);
return INVALID;
}
break;
}
// option value (input, output files)
default:
return OPTION_VALUE;
}
}
else
{
return INVALID;
}
}
int main(int argc, char *argv[])
{
int i, toLen, fromLen;
int fromChars = 0, toChars = 0, outArg = 0, inpArg = 0;
char *to = NULL;
char *from = NULL;
FILE *fileInput = NULL;
FILE *fileOutput = NULL;
char c;
printf("No. of arguments: %d\n", argc);
// flags to help track last read option
bool is_input = false, is_output = false;
for (i = 1; i < argc; i++)
{
const int len = strlen(argv[i]);
enum TokenType type = getTokenType(argv[i]);
//printf("%s %d\n", argv[i], type);
switch (type)
{
case INVALID:
printf("Something went wrong: invalid argument %s\n", argv[i]);
exit(1);
case INPUT_FILE:
if (is_output || is_input)
{
printf("Something went wrong: invalid argument %s\n", argv[i]);
exit(1);
}
is_input = true;
break;
case OUTPUT_FILE:
if (is_output || is_input)
{
printf("Something went wrong: invalid argument %s\n", argv[i]);
exit(1);
}
is_output = true;
break;
case CHARS_TO_BE_REPLACED:
from = calloc(len + 1, sizeof(char));
memset(from, 0, len + 1);
memcpy(from, argv[i] + 2, len - 2);
fromLen = len - 2;
//printf("from: %s\n", from);
//TODO: handle duplicates
break;
case CHARS_TO_REPLACE_WITH:
to = calloc(len + 1, sizeof(char));
memset(to, 0, len + 1);
memcpy(to, argv[i] + 2, len - 2);
toLen = len - 2;
//printf("to: %s\n", to);
//TODO: handle duplicates
break;
case HELP:
if (is_output || is_input)
{
printf("Something went wrong: invalid argument %s\n", argv[i]);
exit(1);
}
help();
exit(0);
case OPTION_VALUE:
if (is_input)
{
is_input = false;
fileInput = fopen(argv[i], "r");
if (!fileInput)
{
printf("Something went wrong: file couldn't be opened %s\n", argv[i]);
exit(1);
}
}
else if (is_output)
{
is_output = false;
fileOutput = fopen(argv[i], "w+");
if (!fileOutput)
{
printf("Something went wrong: file couldn't be opened %s\n", argv[i]);
exit(1);
}
}
else
{
printf("Something went wrong: invalid argument %s\n", argv[i]);
exit(1);
}
break;
default:
exit(1);
}
}
if (fromLen != toLen)
{
printf("From and To strings are different in length: from='%s' to='%s'\n", from, to);
exit(1);
}
// TODO: read input file
// close input file
fclose(fileInput);
// TODO: perform replacement
// TODO: write to output file
// close output file
fflush(fileOutput);
fclose(fileOutput);
// cleanup
free(from);
free(to);
return 0;
}
regarding your question:
Why is my string changing contents after leaving the for loop it is contained in
Your returning a local variable character array, which means the array is on the stack.
The next call will overlay some portion of the stack, which corrupts the original array

Array based search function

I have been trying to create a search function based exclusively on arrays rather than strings. The problem that I currently seem to be finding is that the code is tagging locations, without actually finding the correct letters. The end goal is for the code to find the full word and state how many characters it is into the line. Any help would be greatly appreciated.
int main()
{
int read = 1, i = 0, z = 0, q, o = 0, b;
char a[15];
char letters [] = "HELLOMYNAMEISELDERPRICEANDIHAVECOMETOSHAREWITHYOUTHISMOSTAMAZINGBOOK";
printf("HELLOMYNAMEISELDERPRICEANDIHAVECOMETOSHAREWITHYOUTHISMOSTAMAZINGBOOK\n");
printf("Please type in a word to search for in upper case:\n");
scanf(" %c", &a[1]);
scanf("%c", &a[2]);
if (a[2] != '\n') {scanf("%c", &a[3]); q=2;}
if (read == 1) {if (a[3] != '\n') {scanf("%c", &a[4]); q=3;} else read = 0;}
if (read == 1) {if (a[4] != '\n') {scanf("%c", &a[5]); q=4;} else read = 0;}
if (read == 1) {if (a[5] != '\n') {scanf("%c", &a[6]); q=5;} else read = 0;}
if (read == 1) {if (a[6] != '\n') {scanf("%c", &a[7]); q=6;} else read = 0;}
if (read == 1) {if (a[7] != '\n') {scanf("%c", &a[8]); q=7;} else read = 0;}
if (read == 1) {if (a[8] != '\n') {scanf("%c", &a[9]); q=8;} else read = 0;}
if (read == 1) {if (a[9] != '\n') {scanf("%c", &a[10]); q=9;} else read = 0;}
if (read == 1) {if (a[10] != '\n') {scanf("%c", &a[11]); q=10;} else read = 0;}
if (read == 1) {if (a[11] != '\n') {scanf("%c", &a[12]); q=11;} else read = 0;}
if (read == 1) {if (a[12] != '\n') {scanf("%c", &a[13]); q=12;} else read = 0;}
if (read == 1) {if (a[13] != '\n') {scanf("%c", &a[14]); q=13;} else read = 0;}
if (read == 1) {if (a[14] != '\n') {scanf("%c", &a[15]); q=14;} else read = 0;}
while (i != 1){
printf("line read\n");
if (a[1] == letters[z]){
printf("Found");
for (int p=0; p < q; p++){
o = z+p;
printf("checking for word\n");
if (a[p] == letters[o]){
printf("That bitch");}
else {break;}
}}
z++;
if (letters[z]=='\n'){i = 1;}
}
printf("%c", letters[z]);
printf("hmmm");
}
This redefined code should work for you:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "HELLOMYNAMEISELDERPRICEANDIHAVECOMETOSHAREWITHYOUTHISMOSTAMAZINGBOOK";
char letter[100];
int i, j, k, counter;
i = j = k = counter = 0;
printf("%s\n", str);
printf("Enter a substring to find: ");
scanf("%s", letter);
for (i = 0; str[i]; i++) { // str[i] != '\0'
if (str[i] == letter[j]) {
for (k = i, j = 0; str[k] && letter[j]; j++, k++)
if (str[k] != letter[j])
break;
if (!letter[j]) { // when letter[j] meets false and substring found
printf("\nFound at %d!\n", counter);
return 0;
}
} else {
printf("."); // for decoration
counter++;
}
}
printf(" No matches!\n");
return 0;
}
Sample Output
HELLOMYNAMEISELDERPRICEANDIHAVECOMETOSHAREWITHYOUTHISMOSTAMAZINGBOOK
Enter a substring to find: BOOK
................................................................
Found at 64!

How can I get my Lexical analyzer program to print out more than just seperators?

Im writing a Lexical analyzer to read from a file and describe the text as either identifiers, keywords, separators, or operators. For some reason I am only able to output the separators, unless I delete or comment out the while loop with the print statement for the separators. When I delete that, the program prints out everything else correctly, skipping over the separators.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
int isKeyword(char buffer[]){
char keywords[32][10] = {"auto","break","case","char","const","continue","default",
"do","double","Else","enum","Function","Float","for","goto",
"If","Integer","long","register","Return","short","signed",
"sizeof","static","struct","switch","typedef","union",
"DOWhile","void","Write","while"};
int i, flag = 0;
for(i = 0; i < 32; ++i){
if(strcmp(keywords[i], buffer) == 0){
flag = 1;
break;
}
}
int k, flag2 = 0;
for (k = 0; k<32; ++k){
if(strcmp(keywords[i], buffer) == 0){
flag2 = 1;
break;
}
}
return flag;
return flag2;
}
int main(){
char ch, buffer2[15], operators[] = "+-*/%=";
char ch2, buffer[15], seperators[] = "{}(),;";
FILE *fp;
int i,k,j=0;
fp = fopen("input.txt","r");
if(fp == NULL){
printf("error while opening the file\n");
exit(0);
}
while((ch = fgetc(fp)) != EOF){
for(i = 0; i < 6; ++i){
if(ch == operators[i])
printf("%c is operator\n", ch);
while((ch2 = fgetc(fp)) != EOF){
for(k = 0; k < 6; ++k){
if(ch2 == seperators[k])
printf("%c is seperator\n", ch2);
}
}
if(isalnum(ch)){
buffer[j++] = ch;
}
else if((ch == ' ' || ch == '\n') && (j != 0)){
buffer[j] = '\0';
j = 0;
if(isKeyword(buffer) == 1)
printf("%s is keyword\n", buffer);
else
printf("%s is indentifier\n", buffer);
}
}
}
fclose(fp);
return 0;
}
The problem seems to be the second while loop containing the separator instructions, but I cant seem to figure out how to print that along with everything else.
I think this may help.There is no reason to create an additional char ch, or the buffer, when creating the separators. Just add it onto the end of the previous line. I just split it with a comma.This will clean your code up and allow you to keep the separators with the rest of the while loop code.
#include <stdio.h>
#define KEY 32
#define BUFFER_SIZE 15
int isKeyword(char buffer[])
{
char keywords[KEY][10] = { "auto","break","case","char","const","continue","default", "do","double","else","enum","extern","float","for","goto",
"if","int","long","register","return","short","signed", "sizeof","static","struct","switch","typedef","union", "unsigned","void","volatile","while"};
int i, flag = 0;
for (i = 0; i < KEY; ++i)
{
if (strcmp(keywords[i], buffer) == 0)
{
flag = 1;
break;
}
}
return flag;
}
int main()
{
char ch, buffer[BUFFER_SIZE], operators[] = "+-*/%=", separators[] = "(){}[]<>,";
FILE *fp;
int i, j = 0;
fp = fopen("Text.txt", "r");
while ((ch = fgetc(fp)) != EOF)
{
for (i = 0; i < 6; ++i)
{
if (ch == operators[i])
{
printf(" OPERATOR: %c \n", ch);
}
else if (ch == separators[i])
printf(" SEPARATOR: %c \n", ch);
}
if (isalnum(ch))
{
buffer[j++] = ch;
}
else if ((ch == ' ' || ch == '\n') && (j != 0))
{
buffer[j] = '\0';
j = 0;
{
if (isKeyword(buffer) == 1)
printf(" KEYWORD: %s \n", buffer);
else
printf(" IDENTIFIER: %s \n", buffer);
}
}
}
fclose(fp);
return 0;
}

Program to count lines, char, or words from file

I am writing a program to count words as practice but I am running into a problem where it is incorrectly counting no matter which option I choose.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main(int argc, char **argv){
int totalcount = 0; //hold overall count
for(int i = 2; i < argc; i++){
int count = 0; //hold count for each file
int c; //temporarily hold char from file
FILE *file = fopen(argv[i], "r");
if (strcmp("-c",argv[1])){
while((c = fgetc(file)) != EOF){
count++;
}
}
else if(strcmp("-w",argv[1])){
bool toggle = false; //keeps track whether the next space or line indicates a word
while((c = fgetc(file)) != EOF){
if(!toggle && ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))){
toggle = true;
}
if(toggle && ((c == '\n') || (c == ' '))){
count++;
toggle = false;
}
}
}
else{
while((c = fgetc(file)) != EOF){
if(c == '\n'){
count++;
}
}
}
printf("%d %s", count, argv[i]);
fclose(file);
totalcount += count;
}
if (argc > 3){
printf("%d total", totalcount);
}
return 0;
}
I don't know why my logic for char count doesn't work. I have ran through my logic when writing each section and it doesnt make sense to me why it would not me working. Any help would be greatly appreciated.
strcmp returns 0 when the strings equal, so never enter into the if/else statement
if (strcmp("-c",argv[1]) == 0){ //return value is 0
while((c = fgetc(file)) != EOF){
count++;
}
}
else if(strcmp("-w",argv[1]) == 0){ //return value is 0
bool toggle = false; //keeps track whether the next space or line indicates a word
while((c = fgetc(file)) != EOF){
if(!toggle && ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))){
toggle = true;
}
if(toggle && ((c == '\n') || (c == ' '))){
count++;
toggle = false;
}
}
}
Hope it works for you
You can read file line by line, it may simplify the task
int get_lines_chars(const char *path)
{
/* Open templorary file */
FILE *fp = fopen(path, "r");
if (fp != NULL)
{
ssize_t read;
size_t len = 0;
char *line = NULL;
unsigned int line_no, char_no;
line_no = char_no = 0;
/* Read line-by-line */
while ((read = getline(&line, &len, fp)) != -1)
{
int curr_line = 0;
while (*line)
{
curr_line++;
char_no++;
line++;
}
line -= curr_line;
line_no++;
}
/* Cleanup */
fclose(fp);
if(line) free(line);
printf("File has %d lines and %d chars\n", line_no, char_no);
return 1;
}
return 0;
}

Converting the text of a .txt file

Objective: create a simple code that converts in a .txt file:
every 'I', 'E', 'A', 'S' and 'O' into '1', '3', '4', '5' and '0' respectively.
At first I made it very simply, but it couldn't handle multiple lines of text. So I tried to treat the phrases and lines as a matrix, but I still can't make it work. Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *arquivo;
char frase[100][100];
int i = 0;
int j = 0;
//adress of the initial text file
arquivo = fopen("C:\\Users\\xand\\Desktop\\ex1.txt", "r");
//transfering every line of the file into a matrix
while (!feof(arquivo))
{
fgets(frase[100][i],100, arquivo);
i++;
}
fclose(arquivo);
//converting the letters to numbers
for(j = 0; j < 100; j++)
{
while(frase[i][j] != '\0')
{
if(frase[i][j] == 'i' || frase[i][j] == 'I')
{
frase[i][j] = '1';
}
if(frase[i][j] == 'e' || frase[i][j] == 'E')
{
frase[i][j] = '3';
}
if(frase[i][j] == 'a' || frase[i][j] == 'A')
{
frase[i][j] = '4';
}
if(frase[i][j] == 's' || frase[i][j] == 'S')
{
frase[i][j] = '5';
}
if(frase[i][j] == 'o' || frase[i][j] == 'O')
{
frase[i][j] = '0';
}
i++;
}
}
arquivo = fopen("ex1 criptografado.txt", "w");
//here is where I believe to be the problem
//It doesn't even create the new file. Im not sure if using matrix is the ideal solution to fprintf a multi-lined text to a file
for(j = 0; j < 100; j++)
{
i = 0;
while(frase[i][j] != '\0')
{
fprintf(arquivo, "%s", frase[i][j]);
i++;
}
fprintf(arquivo, "\n");
}
fclose(arquivo);
return 0;
}
The code compiles, but crashes as I try to run it. Can anyone help me with a solution for this?
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *f, *g;
int c;
if ((f = fopen("asdf.txt", "r")) == NULL) {
perror("fopen");
exit(1);
}
if ((g = fopen("asdf1.txt", "w")) == NULL) {
perror("fopen");
exit(1);
}
while ((c = fgetc(f)) != EOF) {
switch (c) {
case 'i':
case 'I':
fputc('1', g);
break;
case 'e':
case 'E':
fputc('3', g);
break;
case 'a':
case 'A':
fputc('4', g);
break;
case 's':
case 'S':
fputc('5', g);
break;
case 'o':
case 'O':
fputc('0', g);
break;
default:
fputc(c, g);
break;
}
}
fclose(f);
fclose(g);
return 0;
}
I've fixed your code. Mainly it was adding '\0' to all unused lines, not printing '\n' at the end of lines because it's put in the string by fgets, replacing frase[i][j] with frase[j][i], and the actual crash: fprintf(arquivo, "%c", frase[j][i]) instead of fprintf(arquivo, "%s", frase[i][j]).
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *arquivo;
char frase[100][100];
int i = 0;
int j = 0;
//adress of the initial text file
arquivo = fopen("C:\\Users\\xand\\Desktop\\ex1.txt", "r");
//transfering every line of the file into a matrix
while (!feof(arquivo)) {
fgets(frase[i], 100, arquivo);
i++;
}
for (; i < 100; i++) {
frase[i][0] = '\0';
}
fclose(arquivo);
//converting the letters to numbers
for (j = 0; j < 100; j++) {
i = 0;
while (frase[j][i] != '\0') {
if (frase[j][i] == 'i' || frase[j][i] == 'I') {
frase[j][i] = '1';
}
if (frase[j][i] == 'e' || frase[j][i] == 'E') {
frase[j][i] = '3';
}
if (frase[j][i] == 'a' || frase[j][i] == 'A') {
frase[j][i] = '4';
}
if (frase[j][i] == 's' || frase[j][i] == 'S') {
frase[j][i] = '5';
}
if (frase[j][i] == 'o' || frase[j][i] == 'O') {
frase[j][i] = '0';
}
i++;
}
}
arquivo = fopen("ex1 criptografado.txt", "w");
for (j = 0; j < 100; j++) {
i = 0;
while (frase[j][i] != '\0') {
fprintf(arquivo, "%c", frase[j][i]);
i++;
}
}
// or simpler:
// for (j = 0; j < 100; j++)
// fprintf(arquivo, "%s", frase[j]);
fclose(arquivo);
return 0;
}
I think there's issue with Logic for using matrix.
You can take a chunk of string and then compare that for all characters - Change the character with Number if it's one of wanted characters (That you need to change), by writing character to stream - See fputc reference for details.
EDIT:
See the answer by #ctn - his code is good example.

Resources