Unexpected result after printing a string in c [duplicate] - c

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++;

Related

How to make a function to input a string with unknown length in c with type void

I am trying to make a function that input an unknown length of a string , but I don't want it to return anything I want it to make changes by using the pointer that I pass.
this was my attempt .
#include <stdlib.h>
#include <stdio.h>
void get(char * string){
int size=1;
string = malloc(size);
char c;
int i=0;
while(1){
c = getchar();
if(c=='\n'){break;}
string[i] = c;
i++;
string = realloc(string , ++size);
}
string[i] = '\0';
}
int main(){
char *buff;
printf("String :");
get(buff);
printf("%s" , buff);
return 0;
}
the output on my gcc windows os :
PE
1- what is the PE
2- what is wrong here
3- is the c=='\n' line good for the test if the user pressed an enter or should i use EOF or something else
I made a few changes to your code so that it would use the pointer passed to it and handle a possible EOF in the input:
#include <stdlib.h>
#include <stdio.h>
void get(char **string){
char *input = NULL;
int result, index = 0;
while (1) {
result = getchar();
if (EOF == result) { printf("\n"); break; }
if ('\n' == result) break;
char *temp = realloc(input , index + 2);
if (NULL == temp) {
perror("Could not increase memory for string");
if (input) free(input);
exit(1);
}
input = temp;
input[index++] = (char) result;
}
if (input) {
input[index] = '\0';
*string = input;
}
}
int main(void) {
char *buff = NULL;
printf("String : ");
get(&buff);
if (buff) {
printf("%s\n" , buff);
free(buff);
}
return 0;
}
Output
$ ./main
String : a short string
a short string
$ ./main
String : input with EOF
input with EOF
Note
I do my best to handle error conditions, but I am not certain I caught everything.

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

Programming in 'C' : How to clear the char array for the next string [duplicate]

This question already has answers here:
function returning pointer to string not working [duplicate]
(2 answers)
Closed 6 years ago.
I try to write a code that can read a text file in a specific order.
The Problem is that the strings overwrite the last string in the Array, but I want that the array is cleared for the next string, however I don't know how to do this.
Here is the text file:
#str_hello_world_test={hello world!test}
#str_hello_world={hello world}
And the output is here:
symbol:str_hello_world_test²`
string:hello world!testtest²`
hello world!testtest²`
symbol:str_hello_worldttest²`
string:hello worldorldttest²`
hello worldorldttest²`
And my Code:
#include <stdio.h>
#include <stdlib.h>
#define MAXBUF 255
//prototypes
void readingFile(FILE* fp);
char* readingSymbol(FILE* fp);
char* readingString(FILE* fp);
int main(void)
{
FILE* fp;
char directory[MAXBUF];
puts("Geben sie ein Verzeichnis ein: ");
gets(directory);
fp = fopen(directory, "r");
readingFile(fp);
system("pause");
return EXIT_SUCCESS;
}
void readingFile(FILE* fp){
int c;
while((c = fgetc(fp)) != EOF){
char* symbol = readingSymbol(fp);
char* string = readingString(fp);
printf("%s\n", symbol);
}
return;
}
char* readingSymbol(FILE* fp){
int c;
int i = 0;
char symbol[MAXBUF];
while((c = fgetc(fp)) != '='){
if(c == '#'){
continue;
}
else{
symbol[i] = (char)c;
i++;
}
}
printf("symbol:%s\n", symbol);
return symbol;
}
char* readingString(FILE* fp){
int c;
int i = 0;
char str[MAXBUF];
while((c = fgetc(fp)) != '}'){
if(c == '='){
continue;
}
else if(c == '{'){
continue;
}
else{
str[i] = (char)c;
i++;
}
}
printf("string:%s\n\n", str);
return str;
}
Your code has a glaring example of undefined behavior. You return dangling references. Turn your warning level as high as possible. Then heed those warnings. A rough (implementation dependent) rationalization for why this is happening, is that the two functions have exactly the same layout of stack frames. So when you call the second one, it fills exactly the same location with a another string.
An immediate fix is to avoid returning a pointer to a buffer, and pass a pointer to a buffer into the function. Then it is responsible for filling it:
char symbol[MAXBUF];
readingSymbol(fp, MAXBUF, symbol);
// ...
void readingSymbol(FILE* fp, size_t const buff_len, char symbol[buff_len]) {
int c;
int i = 0;
while((c = fgetc(fp)) != '='){
if(c == '#'){
continue;
}
else{
symbol[i] = (char)c;
i++;
}
}
printf("symbol:%s\n", symbol);
}
The above is valid C99. If you compile in C89 for some reason, or your compiler doesn't support variable length arrays, change the function signature to be as follows:
void readingSymbol(FILE* fp, size_t const buff_len, char *symbol)

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

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;
}

How can I read a string in c? [duplicate]

This question already has answers here:
How to read string from keyboard using C?
(6 answers)
Closed 9 years ago.
I use this code, but it's not working.
#include <stdio.h>
#include <string.h>
int main() {
char c, *strx = 0;
c = getchar();
while(c != '\n') {
strx = strcat(strx, &c);
c = getchar();
}
printf("%s\n", *strx);
return 0;
}
How can I put a word into a string?
Change
char *strx = 0
to
char strx [256];
For example:
#include <stdio.h>
#include <string.h>
int main()
{
char c, strx[256] = "";
int i = 0;
c = getchar();
while (c != '\n') {
strx[i++] = c;
c = getchar();
}
printf("%s\n", strx);
return 0;
}
You need to allocate space for strx (here on the stack, you can also you malloc)
#include <stdio.h>
#include <string.h>
int main()
{
char c, strx[100] = "";
int i = 0;
c = getchar();
while (c != '\n') {
strx[i++] = c;
if (i == 99)
break;
c = getchar();
}
strx[i] = '\0';
printf("%s\n", strx);
return 0;
}
strcat doesn't work because it expects a null char at the end but it will probably find garbage after the char.
More simply, you can use scanf:
#include <stdio.h>
#include <string.h>
int main()
{
char strx[100] = "";
scanf("%99s", strx);
printf("%s\n", strx);
return 0;
}

Resources