trying to store a text file into an array - arrays

i am trying to read from a text file and store it into an array character by character, ive tested it out by trying to print or check the ii count but it doesn't seem to be storing, any help would be muchly appreciated
char *readFile(char* filename)
{
FILE* f;
int ii = 0;
char* file = (char*)malloc(1000*sizeof(char));
char ch = '\0';
f = fopen(filename,"r");
if(f == NULL)
{
printf("Error opening file '%s'.\n", filename);
}
else
{
while ((ch = fgetc(f)) != EOF)
{
printf("%c",ch);
file[ii] = (char) ch;
ii++;
}
}
/* file[ii] = '\0'; setting last character as null*/
printf("\n");
fclose(f);
free(file);
return file;
}

I have commented out the line containing the code to free the character array before returning, which was basically making the pointer invalid. I have also changed the type of the variable "ch" to int as fgetc() returns integer.
#include <stdio.h>
#include <stdlib.h>
char *readFile(char* filename)
{
FILE* f;
int ii = 0;
char* file = (char*)malloc(1000*sizeof(char));
int ch; //changed to int from char.
f = fopen(filename,"r");
if(f == NULL)
{
printf("Error opening file '%s'.\n", filename);
}
else
{
while ((ch = fgetc(f)) != EOF)
{
// printf("%c",ch);
file[ii] = (char) ch;
ii++;
}
}
/* file[ii] = '\0'; setting last character as null*/
printf("\n");
fclose(f);
//free(file); //commented this line out
return file;
}
int main()
{
char *filename = "sample.txt";
char *file_arr = readFile(filename);
printf("%s \n",file_arr);
return 0;
}

Related

How do I check if every word in a text file is in a dictionary that contains every English word?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char file(FILE *fh, char c[45]);
int lejiko(FILE *lh);
void split(FILE *fh);
int main() {
int choice;
char c[45];
FILE *fh;
FILE *lh;
file(fh, c);
lejiko(lh);
split(fh);
return 0;
}
char file(FILE *fh, char c[45]){
fh = fopen("test.txt", "r");
if (fh != NULL) {
printf("Loaded File");
/* while ((c = fgetc(fh)) != EOF)
putchar(c); */
} else
printf("ERROR");
fclose(fh);
return c;
}
int lejiko(FILE *lh) {
int count = 0;
char t;
lh = fopen("englishWords.txt", "a+");
if (lh != NULL) {
printf("\nLoaded Dictionary");
}
for (t = getc(lh); t != EOF; t = getc(lh))
if (t == '\n')
count = count + 1;
printf("\nYparxoun %d lejeis sto lejiko.\n", count);
return count;
}
void split(FILE *fh) {
char array[45];
char *spl;
fh = fopen("test.txt", "r");
if (fh == NULL)
perror("Error opening file");
else {
while (fgets(array, 45, fh) != NULL) {
printf("%s\n", array);
spl = strtok(array, " ");
while (spl != NULL) {
printf("%s\n", spl);
spl = strtok(NULL, " ");
}
}
fclose(fh);
}
return 0;
}
FILE:I dont know what this is.im.just.testing.out.
Output:
I
dont
know
what
this
is.im.just.testing.out
.
.
This is what I have accomplished so far. I think that the way this will work is by storing every word from the text file and the dictionary in to two matrices and from there by comparing the elements of the matrices.So far i have managed to separate each word whenever there is a space, but when there is punctuation in the text it doesn't seem to work. I have tried multiple ways to remove punctuation from the text, but I cannot get it to work. Also dont mind the functions that just print their names, they will be used for later versions.

Basic File IO in C Produces all a's

I am using CodeBlocks on Windows to compile.
Why the program gives me this answer? Why there are so much as and don't get the answer 123456abcdef?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fp;
char s[100] = "abcdef";
char c1 = '0';
int i = 0;
fp = fopen("ot.txt", "w");
if (fp == NULL) {
printf("file open error");
exit(0);
}
while (s[i] != '\0') {
fputc(s[i], fp);
i++;
printf("%d", i);
}
while (c1 != EOF) {
c1 = fgetc(fp);
putchar(c1);
}
fclose(fp);
}
There are multiple problems in your code:
c1 should be defined with type int to accommodate for all values returned by fgetc(). a char cannot unambiguously store EOF.
You should open the file in write+update mode "w+"
You should rewind the stream pointer before reading back from it for 2 reasons: a seek operation is required between read and write operations and you want to read the characters from the start of the file.
You need to test for EOF after reading a byte with fgetc(), otherwise you will output the EOF converted to unsigned char to stdout before exiting the loop.
It is good style to return 0; from main() to indicate success and non-zero to indicate failure.
Here is a corrected version:
#include <stdio.h>
int main(void) {
FILE *fp;
char s[] = "abcdef";
int i, c;
fp = fopen("ot.txt", "w+");
if (fp == NULL) {
printf("file open error\n");
return 1;
}
i = 0;
while (s[i] != '\0') {
fputc(s[i], fp);
i++;
printf("%d", i);
}
rewind(fp);
while ((c1 = fgetc(fp)) != EOF) {
putchar(c1);
}
printf("\n");
fclose(fp);
return 0;
}

Reading a file word by word with no ending chars

I have this small program in C that reads through a file a compares word by word,
how can I assure that words like "this," won't be read as a word? I would like it to read as "this"
int main(int argc, char *argv[]) {
if(argc != 3)
{
printf("Usage: ./sw <word> <filename> \n");
exit(1);
}
char* word = argv[1];
const char* filename = argv[2];
FILE* file = fopen(filename, "r");
if(file == NULL)
{
printf("Could not open file\n");
exit(1);
}
//Assuming one word can not have more than 250 chars
char w[250], check_eof;
do
{
check_eof = fscanf(file, "%s", w);
if(strcmp(word, w) == 0)
{
printf("W : %s \n", w);
}
} while(check_eof != EOF);
fclose(file);
return 0;
}
You can check if a char belongs to a word like this
int c = fgetc(file);
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
// c belongs to a word
word[n++] = c;
} else {
// end of word
if (strncmp(word, w, n) == 0) {
// word and w match!
}
}
If you #include <ctype.h>, then you can call isalpha(c) instead to test it.
In the code below, I use isalpha() and I copy the result string in a new buffer named res. However, this procedure can be done in-place, but I'll leave now for the sake of simplicity.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h> // for isalpha()
int main(int argc, char *argv[]) {
char* word = "this";
const char* filename = "test.txt";
FILE* file = fopen(filename, "r");
if(file == NULL)
{
printf("Could not open file\n");
exit(1);
}
//Assuming one word can not have more than 250 chars
// ATTENTION, it is 249 chars, do NOT forget of the null terminator
char w[250], res[250];
int check_eof; // should be of type int, for EOF checking
do
{
check_eof = fscanf(file, "%s", w);
// what if 'word' appears as the last word
// in the file? You should check for eof
// right after fscanf()
if(check_eof == EOF)
break;
int i = 0, j = 0;
while (w[i]) // parse what we read
{
if (isalpha(w[i]))
res[j++] = w[i]; // keep only the alphabetic chars
i++;
}
res[j] = '\0'; // it should be a null terminated string
if(strcmp(word, res) == 0) // compare to 'res' now
{
printf("W : %s \n", res);
}
} while(1); // the terminating step is inside the body now
fclose(file);
return 0;
}

How to write text from file to a string in C

I want to write code were the user is asked to write the name of a file. Then I want to analyze the file's content for a symbol, let's say 'e'.
My problem is that I don't know how to start analyzing the file the correct way so that the content can be checked.
int main() {
char c[1000], file_name[1000];
int i;
int s = 0;
FILE *fp;
printf("Enter the name of file you wish to see\n");
gets(file_name);
if ((fp = fopen(file_name, "r")) == NULL){
printf("Error! opening file");
exit(1);
}
if (fp) {
while (fscanf(fp, "%s", c) != EOF) {
printf("%s", c);
}
fclose(fp);
for (i = 0; c[i] != '\0'; ++i) {
puts(c);
if (c[i] == 'e') {
++s;
}
}
printf("\nWhite spaces: %d", s);
_getche();
return 0;
}
}
char line[512]; /*To fetch a line from file maximum of 512 char*/
rewind(fp);
memset(line,0,sizeof(line)); /*Initialize to NULL*/
while ( fgets(line, 512, fp ) && fp !=EOF)
{
/*Suppose u want to analyze string "WELL_DONE" in this fetched line.*/
if(strstr(line,"WELL_DONE")!=NULL)
{
printf("\nFOUND KEYWOD!!\n");
}
memset(line,0,sizeof(line)); /*Initialize to null to fetch again*/
}
If its just a symbol you're looking for, or a char, you can simply use getc() :
int c;
....
if (fp) {
while ((c = getc(fp)) != EOF) {
if (c == 'e') {
// Do what you need
}
}
Or, alternatively, if it's a word you're looking for, fscanf() will do the job:
int c;
char symb[100];
char symbToFind[] = "watever"; // This is the word you're looking for
....
while ((c = fscanf(fp, %s, symb)) != EOF) {
if (strcmp(symb, symbToFind) == 0) { // strcmp will compare every word in the file
// do whatever // to symbToFind
}
}
These alternatives will allow you to search every char or string in the file, without having to save them as an array.

How to read data from a .csv file to a multidimentional array using c language?

In matlab we can do it using the code :
a= csvread('filename.csv');
But using C programming i used the following code but it doesnt works please help :
int main(){
int i,j,temp,m1=0,n=0;
//CSV file reading
int ch;
FILE *fp;
fp = fopen("filename.csv","r"); // read mode
if( fp == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
while( ( ch = fgetc(fp) ) != EOF )
{printf("%d",ch);}
fclose(fp);
return 0;
}
mat[i][j] = ch;
int m1 = i;
int n = j;
}
Please help !
Ok this hasn't been extensively tested but it should read a csv file that has integer values and store them in an (n x m) matrix.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv){
//CSV file reading
int rowMaxIndex,columnMaxIndex;
int **mat;
int *matc;
int i,j,idx;
char part[1024];
char *token;
FILE *fp;
fp = fopen("filename.csv","r"); // read mode
if(fp == NULL){
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
// count loop
rowMaxIndex = 0;
columnMaxIndex = 0;
while(fgets(part,1024,fp) != NULL){
token = NULL;
while((token = strtok((token == NULL)?part:NULL,",")) != NULL){
if(rowMaxIndex == 0){ // only want to increment column count on first loop
columnMaxIndex++;
}
for(idx = 0;idx<strlen(token);idx++){
if(token[idx] == '\n'){ // this assumes there will be a \n (LF) at the end of the line
rowMaxIndex++;
break;
}
}
}
}
// allocate the matrix
matc = malloc(rowMaxIndex*columnMaxIndex*sizeof(int));
mat = malloc(rowMaxIndex*sizeof(int*));
for(idx = 0;idx<rowMaxIndex;idx++){
mat[idx] = matc+idx*columnMaxIndex;
}
// rewind the file to the beginning
rewind(fp);
// read loop
i = j = 0;
while(fgets(part,1024,fp) != NULL){
token = NULL;
while((token = strtok((token == NULL)?part:NULL,",")) != NULL){
mat[i][j] = atoi(token);
j = (j+1)%columnMaxIndex;
}
i++;
}
fclose(fp);
return 0;
}

Resources