How to put text from file into array - c

I need to read text from a file (text of few sentences) and then write down all unique characters. To do that I need to use an array. I wrote this code but it gives me nothing.
#include <stdio.h>
int main(void) {
int i;
FILE *in = fopen("test.txt", "r");
if (in) {
char mas[50];
size_t n = 0;
int ch;
while ((ch = getc(in)) != EOF) {
mas[n++] = (char)ch;
}
fclose(in);
}
for (i = 0; i < 50; i++) {
printf("%c", mas[i]);
printf("\n");
}
return 0;
}

//low level input output commands method
#include <fcntl.h>
int main()
{
int x,i,n,v=1;
char s[256],str;
for (i=1;i<=255;i++)
s[i]='0';
x=open("out.txt",O_RDONLY);
if (x==-1)
{
printf("Invalid file path");
return 0;
}
while (n!=0)
{
n=read(x,&str,1);
s[(int)str]='1';
v=0;
}
close(x);
for (i=1;i<=255;i++)
if (s[i]=='1')
printf("%c",(char)i);
if (v)
printf("Blank file!");
close(x);
return 0;
}

You have a problem with scope. mas was declared within your if block of code and has no visibility outside the if block. Move the declaration for mas outside the block. You need to keep n outside as well i.e.:
int i;
char mas[50];
size_t n = 0;
Next you fail to limit your read to less than 50 chars and will easily overflow mas. Add a check on n:
while ((ch = getc(in)) != EOF && n < 50) {
Finally limit your write of characters to the number read n:
for(i=0;i<n;i++)
That will compile and run. If you had compiled with warnings enabled, the compiler would have identified the scope problem for you. Always compile with -Wall -Wextra at a minimum.

If you intend to read some char's to your array and print out unique one's check the below code
#include <stdio.h>
int main(void)
{
int i,j,flag;
char mas[50];
size_t n = 0;
FILE *in = fopen("test.txt", "r");
if (in) {
int ch;
while ((ch = getc(in)) != EOF && n < 50) {
mas[n++] = (char)ch;
}
fclose(in);
}
for(i=0;i<n;i++)
{
flag = 0;
for(j=i+1;j<n;j++)
{
if( mas[i] == mas[j])
{
flag = 1;
break;
}
}
if(!flag)
{
printf("%c\n",mas[i]);
}
}
return 0;
}

Related

Filling an array of strings with the content of a file

I wrote a short code that should copy the content of a file into an initialized array of strings and then print that array. I get no errors/warnings but still the program doesn't print anything when i run it. The code is the following:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
const int dim = 30;
int main() {
char* arr[dim];
int i = 0;
FILE* fp;
fp = fopen("test.txt", "r+");
if(fp == NULL) {
printf("\nError, breaking...");
return 0;
}
while(i <= dim) {
arr[i] = (char *)malloc(dim*sizeof(char *));
++i;
}
i = 0;
while(fscanf(fp, "%s", arr[i]) != EOF) {
printf("%s: added\n", arr[i]);
++i;
}
}
The file contains a series of words separated only by whitespaces and newline characters.
correct followings and see if it helps
1) initialise i to 0 ie. i=0;
2)
while(i < dim) { } // it should be < as array start with 0

2-Dimensional char array gets filled with wrong input in C

I programm a Whatsapp chat analyser. It is written in C. First, a exportet Whatsapp-chat gets opened by my programme with fopen();...Later it should save the names of the members of the Chat in a temporary array, then they should be written(if the same name isn`t already in the end_array) in the end_array. Else, the the line will be skipped.
Detection of the names of the members:
The chars between - 'my name' : gets saved
07.11.17, 14:38 - Alan (TFO): Alan
The problem: End_Array gets filled with strange chars (Seee Image below) How can I solve this? In the first line should only be 'andisville', in the second line Florian Steger ....
Names:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int printEndArr(int nl, int members, char end_arr3[nl][members]);
int clearArray(int nl, int members, char end_arr3[nl][members]);
int main()
{
FILE *fp;
fp = fopen("datei3.txt", "r");
int a = 0;
int i = 0;
int k = 0;
int c = 0;
int c2 = -1;
int j = 0;
int members = 0;
int m;
int n,strc = 0;
int x,z, zus = 1, nl = 30,zl =0,zle =0,zlex = 0,firc;
//Don't ask me why I formatted the declarations so bad
char chr, *statBeff;
scanf("%d",&members);
char end_arr3[nl][members];
char temp_array[nl];
int counter[members];
clearArray(nl,members, end_arr3);
if(fp == NULL)
{
printf("Achtung die Datei existiert nicht!");//The File doesn`t exist
}
else
{
for(i = 0; chr != EOF; i++) //Read every char of the text file
{
chr = fgetc(fp);
if(chr == '-')
{
chr = fgetc(fp);
if(chr == ' ')
{
j=0;
while((chr = fgetc(fp))!=':')
{
temp_array[j] = chr;
j++;
}
temp_array[j] = '\0'; //The tempArray gets terminated by '\0'
if((strstr(temp_array, "Betreff") == NULL)) //If the temporary array doesn't contain the String 'Betreff'..
{
for(z=0; z < members;z++)
{
if(strcmp(end_arr3[z],temp_array)==0) //Prove if the name of the temp_array is already in the endarray
{
strc = 1;
a--;
break;
}
}
if (strc == 0)//If the temparray isn't in the end array:
{
strcpy(end_arr3[a], temp_array);
}
}
else
{
a--;
}
strc =0;
++a;
if(a == members) //If all members of the whatsapp chat are found the for-loop will be determinated
break;
}
}
}
}
printEndArr(nl,members, end_arr3); //end array gets printed
fclose(fp);
return 0;
}
int printEndArr(int nl, int members, char end_arr3[nl][members])
{
int i,k;
for(i=0;i<members;i++)
{
for(k=0;k<nl;k++)
{
printf("%c",end_arr3[i][k]);
}
printf("\n");
}
return 0;
}
int clearArray(int nl, int members, char end_arr3[nl][members])
{
int i,k;
for(i=0;i<members;i++)
{
for(k=0;k<nl;k++)
{
end_arr3[i][k] = ' ';
}
}
return 0;
}
You've declared end_arr3 backwards:
char end_arr3[nl][members];
where nl is the length of the space for each string and members is the number of strings. But this sets aside space for nl strings each of length members.

I need to write a C program that calls a given function to count the number of characters and digits in a file

I need to write a C program that counts the number of characters and digits in a file. I believe my best attempt is close, but the program must call a given function, mostfrequent(), and I cannot figure out how to implement it into my main so that they work together. Any help would be greatly appreciated. Thank you.
// this is the function my program is required to use.
int mostfrequent(int *a, int length) {
int index = 0;
int max = a[0];
int i;
for (i = 1; i < length; i++) {
if (a[i] > max) {
max = a[i];
index = i;
}
}
return index;
}
// this is my closest attempt at a working program so far, but it does
// not call mostfrequent() which I need it to do.
int main() {
typedef FILE *ptr_file;
int x, i, j;
int length;
char c;
char ch[1000];
int a = 65;
c = getc(ptr_file);
ptr_file = fopen("file.txt", "r");
if (!ptr_file)
return 1;
while (c != EOF) {
scanf(ptr_file, "%s", ch[i]);
i++;
fclose(ptr_file);
}
for (i = 0; i < length; i++) {
for (j = 0; j < length; j++) {
if (a < 116) {
if (char(a) == 'ch[j]')
char max_char_temp=(char)a
count_temp++;
}
if (count_temp > count) {
count = count_temp;
max_char = max_char_temp;
}
return 0;
}
regarding the question: when to call the most_frequent() function.
After you have created an array (which would be 36 entries long of integers), initialize that array to all zeros, then incremented the appropriate entry for each character read from the input file. (note 36 entries allows for a...z + 0...9 so all other characters read from the file should be discarded.
Then pass the array and 36 to the most_frequent() function
then code similar to the following could do the job:
#include <stdio.h>
#include <stdlib.h>
#include <ctypes.h> // isalpha(), isdigit(), toupper()
#define NUM_ALPHA (26)
int main( void )
{
int array[36] = {'\0'};
//...open file, etc
//then assure all processed characters are upper case or numeric
// and update the count in the array
int ch;
while( ch = getc( file ) != EOF && '\n' != ch)
{
if ( isalpha(ch) )
{
ch = toupper(ch);
array[ch - 'A']++;
}
else if (isdigit(ch) )
{
array[ (ch-'0') + NUM_ALPHA ]++;
}
}
int index = mostfrequent( array, sizeof(array)/sizeof(array[0]);
//... do what is needed with 'index' for instance
printf( "the highest occurring char is:" );
if( index < NUM_ALPHA )
{
printf( "%c\n", index+'A' );
}
else
{
printf( "%d\n", (index-NUM_ALPHA)+'0');
}
fclose( file );
return 0;
}
however, note that mostfrequent() only returns the index to the first entry encountered with the max value, when there are multiple entries with the same max value.

printing substrings in a file

So I want to write a program which would print out a text line that contains a certain word from a file. e.g. if I was looking for a word 'linux' it would print out
2 computers called linux00, linux01 and linux02. 5 manager,"
said linux00. "Hello linux00," said 7 here to see us?" said
linux01. "Well," said the 10 linux02. "You're all going to be
unplugged," said 12 goooooooooooo..." said linux00.
from a story.txt:
Once upon a time, there were three little computers called
linux00, linux01 and linux02. One day, the nice computer manager
came into the Linux Laboratory. "Hello nice computer manager,"
said linux00. "Hello linux00," said the nice computer manager.
"What brings you here to see us?" said linux01. "Well," said the
nice computer manager, "I've got bad news and I've got good
news." "What's the bad news?" said linux02. "You're all going to be
unplugged," said the nice computer manager. "What's the
goooooooooooo..." said linux00.
Here's my code:
#include<stdio.h>
#include <stdlib.h>
#define ARR_LEN 100
int getLine(FILE * fin,char a[],int n)
{
int find = contains("linux", 5, a, ARR_LEN);
int count;
int i;
i = 0;
char c = getc(fin);
while(c != '\n')
{
a[i] = c;
// printf ("%c", a[i]);
//i = 0;
if (a[i] == EOF){
return EOF;
}
if (find == 1)
{
printf("%c", c);
c = getc(fin);
}
i = i + 1;
}
if(a[i]=='\n')
{
if ((i - 1) > ARR_LEN) {
printf("warning msg: length is over array bounds\n");
}
// printf("length of line is: %d\n", i - 1);
//printf("%c", a[i]);
i = i + 1;
//printf("\n");
return i - 1;
}
}
int contains(char target[], int m, char source[], int n) {
int flag = 0; // the source originally does not contain the target
int i;
for(i = 0; i < n; i++) { // go through each character of the source string
int targetIndex = 0;
int j;
/*check if the preceding characters of the source string are a substring
that matches the target string*/
for(j = i; j < n && targetIndex < m; j++) {
if(target[targetIndex] == source[j]) {
targetIndex += 1;
if(targetIndex == m) { // the 'target' has been fully found
flag = 1;
break;
}
}
else
{
break;
}
}
if(flag == 1) // 'target' is already found, no need to search further
{
break;
}
}
return flag;
}
main(int argc,char ** argv)
{
setbuf(stdout,NULL);
char a[ARR_LEN];
FILE * fin;
if(argc<2){
printf("wrong number of arguments\n");
exit(0);
}
fin = fopen(argv[1], "r");
if (fin == NULL) {
printf("Cannot open %s\n", fin);
exit(0);
}
int t = 0;
int j = 0;
int find = contains("linux", 5, a, ARR_LEN);
while (j != EOF)
{
t = t + 1;
printf("%d ", t);
j = getLine(fin,a,ARR_LEN);
printf("\n");
}
fclose(fin);
}
The getLine function is alright and it prints out a text with a line number in front all good. But the problem is with this
if (find == 1)
{
printf("%c", c);
c = getc(fin);
}
part, where I want the program to only print out the line if "contains" finds a match in that line.
Thanks for any help & sorry for a long post!!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char sentence[500];
char word[10] = "linux";
FILE* fp1 = fopen("strstr.txt","r");
if(fp1 == NULL)
{
printf("Failed to open file\n");
return 1;
}
while((fscanf(fp1,"%[^\n]\n",sentence)>0))
{
if(strstr(sentence,word)!=NULL)
printf("%s\n\n",sentence);
}
}

Convert a set of chars to int from a file

I'm reading:
22:5412:99:00 (...)
From a text file using (ch=fgetc(fp)) != EOF because I don't have only those numbers to read.
Identifying a number is easy with if(ch >= 48 && ch <= 57) but the thing is I want to put those numbers 22, 5412 into an array of integers. However when I read a char it reads part of number since each number is char.
It gets 2 (and not 22 like I want to) and in the next iteration reads the other 2. How can I save each set of numbers into it's own integer?
I hope I was clear enough, thanks!
My idea is to read in each char, and if it is a digit append it to a buffer. Whenever we get a non-digit, we just read the contents of the buffer as a string using sscanf, and clear the buffer for the next value.
#include <stdio.h>
#include <stdlib.h>
int read_buffer(char* buffer, int* sz)
{
int ret;
if (*sz==0) return 0;
buffer[*sz]='\0'; //end the string
sscanf(buffer,"%d", &ret); //read the contents into an int
*sz=0; // clear the buffer
return ret;
}
int main()
{
char buffer[1000];
int sz=0;
char ch;
FILE* input=fopen("input.txt","r");
// "input.txt" contains 22:5412:99:00
while ((ch=fgetc(input))!=EOF)
{
int number;
if (isdigit(ch))
{
buffer[sz++]=ch; // append to buffer
}
else
{
printf("Got %d\n",read_buffer(buffer,&sz)); // read contents of buffer and clear it
}
}
if (sz) // check if EOF occured while we were reading a number
printf("Got %d\n",read_buffer(buffer,&sz));
fclose(input);
return 0;
}
You would need to store the numbers as a string or a char* and use atoi to actually convert it to a number. http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/
Assuming your pattern is of the type NN:NNNN:NN:NN, parse on the delimiter, feeding characters into a buffer:
int idx = 0, nIdx = 1;
int firstN, secondN, thirdN, fourthN;
char buf[5];
...
while ((ch=fgetc(fp)) != EOF) {
if (ch != ':') {
buf[idx++] = ch;
}
else {
buf[idx] = '\0';
idx = 0;
switch (nIdx++): {
case 1: firstN = atoi(buf); break;
case 2: secondN = atoi(buf); break;
case 3: thirdN = atoi(buf); break;
}
}
}
buf[idx] = '\0';
fourthN = atoi(buf);
...
I did a full program out of the previous post -- and some testing :-)
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
/* fill `array` with at most `siz` values read from the stream `fp` */
/* return the number of elements read */
size_t fillarray(int *array, size_t siz, FILE *fp) {
int ch;
size_t curr = 0;
int advance_index = 0;
while ((ch = fgetc(fp)) != EOF) {
if (isdigit((unsigned char)ch)) {
array[curr] *= 10;
array[curr] += ch - '0';
advance_index = 1;
} else {
if (advance_index) {
advance_index = 0;
curr++;
if (curr == siz) { /* array is full */
break;
}
}
}
}
return curr + advance_index;
}
int main(void) {
int array[1000] = {0};
int n, k;
n = fillarray(array, 1000, stdin);
if (n > 0) {
printf("%d values read:\n", n);
for (k=0; k<n; k++) {
printf(" %d", array[k]);
}
puts("");
} else {
fprintf(stderr, "no data read\n");
}
return 0;
}
And a test run
$ ./a.out
24555:76423 foobar 76235 jgfs(8) jhg x86-64 passw0rd RS232
[CTRL+D]
8 values read:
24555 76423 76235 8 86 64 0 232

Resources