I need to read a file until "over" is encountered [duplicate] - c

This question already has an answer here:
C: How to compare two strings? [duplicate]
(1 answer)
Closed 9 years ago.
I have trouble reading a file until a word is encountered, this is what I have done but I don't think the if statement allows strings to be written within them
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
int i;
char buffer[100];
FILE *fptr = fopen("testing.txt", "r");
if(fptr != NULL)
printf("file opened successfully\n");
else {
printf("file error occured\n");
printf("terminating program...\n");
return 0;
}
while (fgets(buffer, 100,fptr))
{
if(buffer != "over") {
printf("%s ", buffer);
}
else
return 0;
}
}

When you do
if(buffer != "over")
you compare two pointers, the pointer to buffer and the pointer to the string literal "over". Those pointers will never be the same.
To compare strings in C you have to use the strcmp function.

For comparing string you need to use strcmp() function. You can't do directly by if(buffer != "over"). It compares pointers instead of stings.

#include <stdio.h>
#include <string.h>
int isEndWith(const char *string, const char *word){
int len = strlen(string);
int lenw = strlen(word);
if(len >= lenw)
return strncmp(string + len - lenw, word, lenw)==0;//or use strcmp
else
return 0;
}
int main(void){
char str1[] = "how are you over i am busy over\n";
char str2[] = "how are you over i am busy over\n";
char *p;
if(p=strchr(str1, '\n'))
*p = '\0';//chomp \n
if(!isEndWith(str1, "over"))//check case end string
printf("%s", str1);
else {
int len = strlen(str1);
str1[len - 4] = '\0';// 4 : strlen("over");
printf("%s\n", str1);//print "how are you over i am busy \n"
}
if(p=strstr(str2, "over"))//check case contain string
*p = '\0';
printf("%s\n", str2);//print "how are you \n"
return 0;
}

Related

Is there a way combine a specific number of chars from fgetc?

I have found some information about strcat and experimented with it but it doesn't work the way i expected for example :
char a = 'a', b = 'b';
strcat(a,b);
printf("%c", a);
this will produce an error "initialization of 'char' from 'char *' makes integer from pointer without a cast". Is there a way to unite chars until the wanted word is complete and store it in 1 variable? Or am i going completely wrong about this. The purpose of the code is to read an xml file and build a tree with the tags.
Any help is or advice is very much appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int count = 0;
char c, word;
FILE *file = fopen("example.xml", "r");
if (file == NULL) {
return 0;
}
do {
c = fgetc(file);
if (c == '<') {
count = 1;
}
if (c == '>') {
count = 0;
printf(">");
}
if (count == 1) {
printf("%c", c);
}
if (feof(file)){
break ;
}
} while(1);
fclose(file);
return(0);
}
I'm not sure exactly what you're trying to accomplish, but you could try something like the following, which will print every <tag>, i.e., every string in the file between <...>'s , and will also accumulate them in an array of strings called tags[]. And note that you'd might want to add checks that avoid going over the 99 chars/tag and 999 tags total. But if this isn't anything like what you're actually trying to do, maybe clarify the question.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int ntags=0, ichar=0,nchars=0;
char c='\000', tags[999][99];
FILE *file = fopen("example.xml","r");
if (file==NULL) return(0);
while((ichar=fgetc(file))!=EOF) {
c = (char)ichar;
if (nchars==0 && c!='<') continue;
tags[ntags][nchars++] = c;
if (c=='>') {
tags[ntags][nchars] = '\000';
printf("tag#%d = %s\n",ntags+1,tags[ntags]);
nchars=0; ntags++; }
}
/* do you now want to do anything with your tags[] ??? */
fclose(file);
return(0);
}
You are trying to use a function, those parameters are char *
char *strcat(char *dest, const char *src)
but you gave strcat a char but it wants a char*
int main()
{
char str1[20] = "this";
char str2[] = "is";
strcat(str1, str2);
printf("%s", str1);
return 0;
}
this is the way i thinkt you want it

Unexpected result after printing a string in c [duplicate]

This question already has answers here:
Why does fgetc() return int instead of char?
(2 answers)
Closed 1 year ago.
The code is -
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *filevar;
filevar = fopen("file", "r");
char copy [100];
int i = 0;
while(1)
{
char ch = fgetc(filevar);
if(ch==EOF)
{
break;
}
copy[i] = ch;
i++;
}
printf("\n%s", copy);
fclose(filevar);
return 0;
}
When I run it the out put I get is
textblablaâ– a
file content is -
textblabla
Changing the file content changes the random charecters at end
Two main issues.
ch has to be int
You do not null character terminate the string
int ch = fgetc(filevar);
if(ch==EOF)
{
copy[i] = 0;
break;
}
copy[i] = ch;
i++;

Odd printf behaviour [duplicate]

This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Returning an array using C
(8 answers)
Closed 3 years ago.
I have implemented my own strchr() function in C.
When calling the function and saving the output into a pointer I go ahead and print the stream of chars and the result looks fine. However, after calling a printf(), my stream of chars gets cut off for some reason. Does anyone understand why?
Here is my code:
#include <stdio.h>
#include <string.h>
char *mon_strchr(const char *chaine, int car)
{
int j = 0, i;
char *pbuff, buff[256];
pbuff = buff;
for (i = 0; chaine[i] != '\0'; i++)
{
if ((int)chaine[i] == car)
break;
i++;
}
for (i; chaine[i] != '\0'; i++)
{
buff[j] = chaine[i];
j++;
}
return pbuff;
}
int main()
{
const char str[] = "http://www.tutorialspoint.com";
const char ch = '.';
char *ret;
ret = mon_strchr(str, ch);
printf("%s\n", ret);
printf("String after |%c| is\n", ch);
printf("%s\n", ret);
return (0);
}
And this is the output:
.tutorialspoint.com
String after |.| is
.tutoria

Substring in C Programming

I just want to extract the particular word from the string.
My program is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 100
int main() {
FILE *f;
char buffer[100];
char buf[100];
int count=0;
char res[100];
f=fopen("1JAC.pdb","rb");
while(fgets(buffer,BUFFER_SIZE,f))
{
if(strncmp(buffer,"ATOM",4)==0 && strncmp(buffer+13,"CA",2)==0 && strncmp(buffer+21,"A",1)==0)
{
strcpy(buf,buffer);
}
printf (buf);
Output of the program is
ATOM 1033 CA LEU A 133 33.480 94.428 72.166 1.00 16.93 C
I just want to extract the word "LEU" using substring. I tried something like this:
Substring(17,3,buf);
But it doesn't work...
Could someone please tell about the substring in C.
Memcpy seems to be best way to do this ...
memcpy( destBuff, sourceBuff + 17, 3 );
destBuff[ 3 ] = '\0';
Please remember to add the null terminators if needed (as I have done in the example).
Also this has been answered before, several times on Stack-overflow
(Get a substring of a char*)
//Use the following substring function,it will help you.
int main(int argc, char *argv[])
{
FILE *filepointer;
char string[1700];
filepointer=fopen("agg.txt", "r");
if (filepointer==NULL)
{
printf("Could not open data.txt!\n");
return 1;
}
while (fgets(string, sizeof(string), filepointer) != NULL)
{
char* temp=substring(string,17,3);/*here 17 is the start position and 3 is the length of the string to be extracted*/
}
return 0;
}
char *substring(char *string, int position, int length)
{
char *pointer;
int c;
pointer = (char*) malloc(length+1);
if (pointer == NULL)
{
printf("Unable to allocate memory.\n");
exit(1);
}
for (c = 0 ; c < length ; c++)
{
*(pointer+c) = *(string+position-1);
string++;
}
*(pointer+c) = '\0';
return pointer;
}
char out[4] = {0};
strncpy(out, buf+17, 3);

Storing the buffer of fgets in Array

I'm new to C (coming from Java) and naturally that poses some difficulties. I would like to write just a short program that reads in char-Arrays from stdin and stores the individual strings in an array. After reading in the strings I just want to have them printed out, but that's when it gets really confusing for me.
Here's my code:
#include <stdlib.h>
#include <stdio.h>
int main(){
char **stringarray[2];
char buffer[5];
int i = 0;
while( i < 2 && fgets(buffer, 5, stdin) != NULL){
char *tmp = buffer;
stringarray[i] = &tmp;
i++;
}
for(int i = 0; i < 2; i++){
printf("%s\n", &stringarray[i]);
}
return 0;
}
The first part does in fact compiles (i.e. the part before the print out). I understand that my stringArray has to be an array of char pointers, because that's what a char array basically is in c. It's a pointer to the first character. At first I just wrote
while( i < 2 && fgets(buffer, 5, stdin) != NULL){
stringarray[i] = buffer;
i++;
}
which also compiled, but of course then I have one pointer that points to buffer, which will only save the last string that has been read.
What do I have to do that I can store a simple array of strings?
I suggest you change your code as following.
#include <stdlib.h>
#include <stdio.h>
#include <string.h> /* to use strdup function */
int main(){
char *stringarray[2]; /* I don't understand why you use pointer to pointer than pointer, char **stringarray[2]; */
char buffer[6]; /* I suggest 6 than 5, because string has terminate byte in C */
int i = 0;
while( i < 2 && fgets(buffer, 5, stdin) != NULL){
stringarray[i] = strndup(buffer, 5);
i++;
}
for(int i = 0; i < 2; i++){
printf("%s\n", stringarray[i]); /* changed stringarray */
}
return 0;
}
char **stringarray[2]; is like char ***stringarray because an array is like a pointer to the first value of the array.
printf wants a char* and &stringarray[i] is a char**
if a string is an array then an array of strings is an array of array.
So the code is :
int main()
{
char stringarray[2][5];//array of (array of char)
char buffer[5];
int i = 0;
while( i < 2 && fgets(buffer, 5, stdin) != NULL)
{
strcpy(stringarray[i],buffer); //copies the buffer into the string array
i++;
}
for(i = 0; i < 2; i++)
{
printf("%s\n", stringarray[i]);
}
return 0;
}
If you didn't want to use buffer you could just writte :
while( i < 2 && fgets(stringarray[i], 5, stdin) != NULL)
{
i++;
}
Note that you get 5 characters, the last one will be the NUL terminator \0. And because you have to press enter to validate, the one before \0 will be Line Feed\n. And you will only have 3 characters you really wanted.
You can do it using dynamic allocation technique as below .
#include<stdio.h>
#include<malloc.h>
#include <stdlib.h>
int main()
{
int num;
int len=0;
int i;
printf("Enter the number of elements to be entered ");
scanf("%d",&num);
//Allocate memory for the array of strings
char **var=(char **)malloc(num * sizeof(char *));
for(i=0;i<num;i++)
{
printf("Enter the string : ");
//get strings using getline
getline(&var[i],&len,stdin);
}
for(i=0;i<num;i++)
{
printf("String %d : %s \n",i,var[i]);
}
free(var);
}

Resources