How to read and compare character 255 in C - c

I need to write a code that searches all the aparition of a string in a file. Recently, my teacher told me to search string (char)255(char)255 in a file with the same string. The problem is that I can not read those characters and badly, I cannot distinguish or compare those caracter to EOF; My code for searching the given string in a file is :
//problema 14
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char b;
int k=0;
if(argc!=3) {
fprintf(stderr,"Utilizare: %s fisier sir\n",argv[0]);
return 1;
}
if(argv[2][0]=='\0'){
fprintf(stderr, "String vid\n");
return 1;
}
FILE *f;
f=fopen(argv[1],"r");
if (!f)
{
perror(argv[1]);
return 1;
}
int i=0;
while((b = fgetc(f))!=EOF)
{
if(b==argv[2][i]) i++;
else {
fseek(f,-i, SEEK_CUR);
i=0;
}
if(argv[2][i]=='\0'){
k++;
fseek(f,-i+1, SEEK_CUR);
i=0;
}
}
printf("\nSULFUS %d APPEARANCES\n",k);
return EXIT_SUCCESS;
}
what can I do with this code to work on comparint string of (char)255 characters?

The trick is to realize that fgetc returns an int.
So, change the data type of bto int!

But then, "while" does nothing, because it seems that 255 is also recognized as EOF or it goes infinite. I tried also with int but I couldn't figure out much...This teacher is like a compilator, he likes to put you in trouble.

Related

How to use fscanf to read a text file including many words and store them into a string array by index

The wordlist.txt is including like:
able
army
bird
boring
sing
song
And I want to use fscanf() to read this txt file line by line and store them into a string array by indexed every word like this:
src = [able army bird boring sing song]
where src[0]= "able", src[1] = "army" and so on. But my code only outputs src[0] = "a", src[1] = "b"... Could someone help me figure out what's going wrong in my code:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *fp = fopen("wordlist.txt", "r");
if (fp == NULL)
{
printf("%s", "File open error");
return 0;
}
char src[1000];
for (int i = 0; i < sizeof(src); i++)
{
fscanf(fp, "%[^EOF]", &src[i]);
}
fclose(fp);
printf("%c", src[0]);
getchar();
return 0;
}
Pretty appreciated!
For example like this.
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define MAX_ARRAY_SIZE 1000
#define MAX_STRING_SIZE 100
int main(int argc, char *argv[]) {
FILE *fp = fopen("wordlist.txt", "r");
if (fp == NULL) {
printf("File open error\n");
return 1;
}
char arr[MAX_ARRAY_SIZE][MAX_STRING_SIZE];
int index = 0;
while (1) {
int ret = fscanf(fp, "%s", arr[index]);
if (ret == EOF) break;
++index;
if (index == MAX_ARRAY_SIZE) break;
}
fclose(fp);
for (int i = 0; i < index; ++i) {
printf("%s\n", arr[i]);
}
getchar();
return 0;
}
Some notes:
If there is an error, it is better to return 1 and not 0, for 0 means successful execution.
For a char array, you use a pointer. For a string array, you use a double pointer. A bit tricky to get used to them, but they are handy.
Also, a check of the return value of the fscanf would be great.
For fixed size arrays, it is useful to define the sizes using #define so that it is easier to change later if you use it multiple times in the code.
It's reading file one character at a time, Which itself is 4 in size like we see sizeof('a') in word able. Same goes for 'b' and so on. So one approach you can use is to keep checking when there is a space or newline character so that we can save the data before these two things as a word and then combine these small arrays by adding spaces in between and concatenating them to get a single array.

Get the user to enter a name but using file stream *fp

I am a beginner in c so I have a problem with get the user to input last name, a comma & then first name. However it will pass to the function call
int get_name(FILE *fp)
in my main function. I have a problem either if I have to use the arguments parameters.
Example, main (int argc, char *argv[])) or just main (void))
and from what I have been searching so far, FILE*fp cannot get the user to enter from stdin it only use to open the file(?) BUT I am required to get the user to input from keyboard and pass to the function. I have written some codes. but they don't seem to work but I am going to put down on here the one I am sure that I need a few changes most.
#define LINESIZE1024
int main(void){
FILE *fp;
char line[LINESIZE];
char first;
char last;
char comma;
while(1){
if(!fgets(line,LINESIZE,stdin)){
clearerr(stdin);
break;
}
if(fp = (sscanf(line,"%s %s %s",&last,&comma,&first)==3))
get_name(fp);
if(get_last_first(fp)== -1)
break;
printf("Please enter first name a comma and then last name");
}
BUT I got an error saying I can't use pass it from pointer to an integer. and many MORE but I accidentally closed my concolse and all the errors that appeared while I was trying to fix are gone. So please give me some ideas.
What about seconde code
while(1){
if(!fgets(line,LINESIZE,fp)){
clearerr(stdin);
break;
}
if(sscanf(line,"%s %s %s",last,comma,first)==3)
get_last_first(fp);
return 0;
}
It gave me errors too. fp,last,first,comma used uninitialized in this function
OK so I think I have fixed the previous problem now. However it doesn't print the name back if the name is given correctly. Here is my fixed main code.
int main(void){
FILE *fp = stdin;
char line[LINESIZE];
char first[16];
char last[16];
while(1){
if(!fgets(line,LINESIZE,stdin)){
clearerr(stdin);
break;
}
if(sscanf(line,"%s ,%s",last,first)==2)
if(get_name(fp)==2)
printf("Your name is: %s %s\n", first, last);
}
return 0;
}
here is my function.
int get_name(FILE *fp){
char line[LINESIZE];
char last[16], first[16];
int n;
/* returns -1 if the input is not in the correct format
or the name is not valid */
if(fgets(line, LINESIZE, fp) == NULL) {
return -1;
}
/* returns 0 on EOF */
if((n = sscanf(line, " %[a-zA-Z-] , %[a-zA-Z-]", last, first)) == EOF) {
return 0;
}
/* prints the name if it's valid */
if((n = sscanf(line, " %[a-zA-Z-] , %[a-zA-Z-]", last, first)) == 2) {
return 2;
}
return 1;
}
I thank you people so much for taking time to read and help me. Please don't be mean :)
Seems that you are making it more complicated than needed. Don't call fgets and scanf in main. Only do that in the function get_name.
It can be something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINESIZE 1024
int get_name(FILE *fp)
{
char line[LINESIZE];
char* t;
if(!fgets(line, LINESIZE,fp))
{
printf("Error reading input\n");
return 0;
}
t = strstr(line, ",");
if (t)
{
*t = '\0';
++t;
printf("First: %s - Last: %s\n", line, t);
return 2;
}
printf("Illegal input\n");
return 0;
}
int main(int argc, char **argv)
{
get_name(stdin);
return 0;
}
If you later decide that you want to read from a file, you can reuse the function get_name without changing it at all. All you need is to change main. Like:
int main(int argc, char **argv)
{
FILE* f = fopen("test.txt", "r");
if (f)
{
get_name(f);
fclose(f);
}
else
{
printf("Open file failed\n");
}
return 0;
}
If you want to read from the keyboard, read from stdin or use scanf, which internally reads from stdin. If you want to read from a file instead, use FILE *fp, but don't forget to open the file and check if it was successful (you'll find lots of tutorials for this).
Further, when reading in strings, you need an array of characters, not a single one. Note further, that scanf can already deal with formats like "everything that is not a ',' then a ',' then a string. Note that format "[^,]" means "any character except a ',':
So you could adapt the code as follows:
#define LINESIZE 1024
int main(void){
char line[LINESIZE];
char first[LINESIZE];
char last[LINESIZE];
while(fgets(line,LINESIZE,stdin)) {
if(sscanf(line,"%[^,],%s",last,first)==2) {
printf("Read in %s ... %s\n",last,first);
}
else {
printf("Please enter first name a comma and then last name");
}
}
return 0;
}
And if your professor is picky concerning the "use FILE*", you could write:
FILE *fp = stdin;
...
while(fgets(line,LINESIZE,fp)) {
...

Using fscanf to store words from file in an array

I am trying to write a program for some classwork that reads in a file using fscanf, and then stores each word into an array with one word in each element. Then I need to print each element of the array out on to a new line on the console.
The getty.txt file has the Gettysburg address in it with appropriate spacing, punctuation, and is multiline.
What I think is happening is that the entire text is being stored in the first element of the array, but I am not 100% sure as I am still learning to debug and write in C.
Any advice as to what I am doing wrong would be great! I currently only seem to be getting the last word and some extra characters.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void readFile();
void writeFile(char* buffer, int bufferlen);
FILE *fpread;
FILE *fpwrite;
char filebuffer[1000];
int filebufferlen = 0;
int main(int argc, char *argv[]) {
fpwrite = fopen("csis.txt", "w");
readFile();
writeFile(filebuffer, filebufferlen);
fclose(fpwrite);
return 0;
}
void readFile() {
char c;
filebufferlen = 0;
if(!(fpread = fopen("getty.txt", "r"))){
printf("File %s could not be opened. \n", "getty.txt");
fprintf(fpwrite,"File %s could not be opened. \n", "getty.txt");
exit(1);
}
while (!feof(fpread)) {
fscanf(fpread, "%s", filebuffer);
filebufferlen++;
}
}
void writeFile(char* filebuffer, int filebufferlen) {
for (int i = 0; i < filebufferlen; ++i){
printf("%c\n", filebuffer[i]);
}
}
After fixing the compile problems:
the code does not contain any code nor data declarations to contain an array of 'words.' So naturally, nothing but the last word is actually saved so it can be printed out.

Find instance of different character in a file

In this program, I want to print out the instance of different characters in a file. The output will contain three variable, the number of occurrence, the hex of the letter, and the letter itself. Can someone help me with this? I am stuck!
Results of program should be something like this:
10 instance of character 0x4s (O)
10 instance of character 0x51 (W)
10 instance of character 0x51 (Y)
2 instances of character 0x65 (a)
18 instances of character 0x67 (c)
16 instances of character 0x81 (d)
//here is my program.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char FILE_NAME[] = "input.txt";
int main(argc, *argv[]) {
char temp;
char count[255];
FILE *in_file;
int ch;
fp = fopen(FILE_NAME, "r");
if (in_file == NULL) {
printf("Can not open %s \n", FILE_NAME);
exit(0);
}
while (!feof(fp)) {
ch = fgetc(fp);
if(strchr(count, ch)!= NULL)
{
}
}
printf("%d instance of character (%c)", count);
fclose(in_file);
return (0);
}
Here's what you want (based on your code, with many comments by me):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h> // you need this to use isupper() and islower()
const char FILE_NAME[] = "input.txt";
int main(int argc,char *argv[]) {
char temp;
unsigned count[52] = {0}; // An array to store 52 kinds of chars
FILE *fp;
int i;
fp = fopen(FILE_NAME, "r");
if (fp == NULL) {
printf("Can not open %s \n", FILE_NAME);
exit(0);
}
while((temp = fgetc(fp)) != EOF) { // use this to detect eof
if(isupper(temp))
count[26+(temp-'A')]++; // capital letters count stored in 26-51
if(islower(temp))
count[temp-'a']++; // lower letters count stored in 0-25
}
fclose(fp); // When you don't need it anymore, close it immediately.
for(i = 0; i < 26; i++)
if(count[i])
printf("%d instance of character 0x%x (%c)\n", count[i], 'a'+i, 'a'+i);
for(; i < 52; i++)
if(count[i])
printf("%d instance of character 0x%x (%c)\n", count[i], 'A'+i-26, 'A'+i-26);
return (0);
}
Your array count is not a string, so using strchr() on it is not a good idea. Also, it's of type char, so it has very limited range for larger files.
You should probably use something like unsigned long count[256]. Make sure to initialize the counts to 0 before starting.
Also, don't use feof(). Just loop calling fgetc() until the returned character (which, correctly, has type int) is EOF. Cast it to something positive before using it to index into count for the increment.

copying text to a character array from a text file in C?

Hey there, How do I go about copying text inside a text file into a multidimensional character array?
supposing the text file( text_file.txt) contained
this is the first line
this is the second line
this is the third line
#include <stdio.h>
int main(void){
FILE *f;
f=fopen("text_file.txt","r");
if (f==NULL){
printf("invalid!");
return 1;
}
else {
printf("successful");
}
char copied_text[80][80];
while (!feof(f)){
int i=0,j=0;
fgets(copied_text[i][j],"%s",f);
i++;
}
return 0;
}
-thank you.
I think your code almost work.
Just move the declaration of int i out of the loop.
Change the first parameter of fgets to copied_text[i] because it needs a pointer here.
Change the second parameter of fgets to 80 because it should be a int indicates the acceptable string length.
#include <stdio.h>
int main(void){
FILE *f;
f=fopen("text_file.txt","r");
if (f==NULL){
printf("invalid!\n");
return 1;
}
else {
printf("successful\n");
}
char copied_text[80][80];
int i=0;
while (!feof(f)){
fgets(copied_text[i],80,f);
++i;
}
for(int i = 0; i <3; ++i)
printf("%s\n", copied_text[i]);
return 0;
}

Resources