L
Logan Lee
Hi. I've written a small program to learn to write in C. But unfortunately the output is all jumbled up and not nice.
/* read_file.c
The whole point of this code is to read the entire content from a file then arrange the data as a single string. */
#include <stdio.h>
char* returnArrayFromFile(char* file_name) {
// Try opening a file
FILE *text_file=fopen(file_name,"r");
// Total number of characters in the file.
int m=0;
while(feof(text_file)==0) {
fgetc(text_file); m++;
}
fclose(text_file);
fopen("text_file","r");
char file_content[m];
int i=0;
while(i<m) {
fscanf(text_file, "%c", &file_content[i++]);
}
fclose(text_file);
return file_content;
}
/* substring.c
Return B from ABC */
char* getSubstring(char* larger, int a, int b) {
char* smaller=(char *)malloc(sizeof(char) * b);
int i;
for(i=0; i<b; i++) {
if (larger[a+i]=='\0') {
break;
}
smaller=larger[a+i];
}
return smaller;
}
/* main.c */
#include "read_file.h"
#include "substring.h"
int main(int argc, char* argv[]) {
char* file_name=argv[1];
int a=atoi(argv[2]);
int b=atoi(argv[3]);
char* larger=returnArrayFromFile(file_name);
char* smaller=getSubstring(larger, a, b);
printf("%s", smaller);
}
/* Lastly, text_file */
abcdefghi
If I compile them with gcc *.c -o main and execute by
main text_file 3 3
I'm expecting the output
def
But I'm getting others with jumbled characters.
/* read_file.c
The whole point of this code is to read the entire content from a file then arrange the data as a single string. */
#include <stdio.h>
char* returnArrayFromFile(char* file_name) {
// Try opening a file
FILE *text_file=fopen(file_name,"r");
// Total number of characters in the file.
int m=0;
while(feof(text_file)==0) {
fgetc(text_file); m++;
}
fclose(text_file);
fopen("text_file","r");
char file_content[m];
int i=0;
while(i<m) {
fscanf(text_file, "%c", &file_content[i++]);
}
fclose(text_file);
return file_content;
}
/* substring.c
Return B from ABC */
char* getSubstring(char* larger, int a, int b) {
char* smaller=(char *)malloc(sizeof(char) * b);
int i;
for(i=0; i<b; i++) {
if (larger[a+i]=='\0') {
break;
}
smaller=larger[a+i];
}
return smaller;
}
/* main.c */
#include "read_file.h"
#include "substring.h"
int main(int argc, char* argv[]) {
char* file_name=argv[1];
int a=atoi(argv[2]);
int b=atoi(argv[3]);
char* larger=returnArrayFromFile(file_name);
char* smaller=getSubstring(larger, a, b);
printf("%s", smaller);
}
/* Lastly, text_file */
abcdefghi
If I compile them with gcc *.c -o main and execute by
main text_file 3 3
I'm expecting the output
def
But I'm getting others with jumbled characters.