Unknown length of input [duplicate] - c

This question already has answers here:
How can I read an input string of unknown length?
(11 answers)
Closed 7 years ago.
There are several ways how to retrieve string input, e.g getline() , or fgets() but all of them require size of the string as an argument. But what if i want to retrieve string of unknown size? How is it possible using getline() or fgets() in C?

The answer is no. You can't read a string of indeterminate length. You can, however, read one character at a time until you reach the size of the storage space you have allocated in your program. Use fgetc in a loop.
int fgetc(FILE *stream)
Open the stream , read one character at a time, and stop reading when you see your sentinel character, which is probably a newline.

Related

fgets() and text files [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
My book mentions that fgets will read until it meets the (n-1)th character or a character of a new line. By character of new line do we only mean Enter (\n)? I am asking this because what I did was to create a text file on which I started typing in some nonsense, surpassing the character limit of each line meaning that I used more than one lines. After that I used fgets and what I expected was it to read only the characters in the first line of the text file but what it did was read all of them.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char box[5000];
FILE *fp;
fp = fopen("test.txt", "r");
fgets(box, 5000, fp);
puts(box);
}
Test.txt (The text is random that's why it's silly) (285 characters):
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk25kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkggggggggggiiiiiiiiiiiiiiiiiiii
So the result I expected was for it to print only part of the text and actually as many characters as the limit that is set for one line, minus one, (which I think is something above 250). But instead of that, it prints all of them. Note: The same thing happens even I type even more characters in the file.
You seem to be assuming that there's an upper limit, perhaps 255 characters, on the length of a line in a text file. C imposes no such limit, except indirectly by using int as the size argument to fgets.
Your program defines a 5000-character array and calls fgets with a length argument of 5000. That means it can read a single line of up to 5000 characters (or close to that; I'm ignoring a couple of off-by-one issues for the '\n' and '\0' characters). The input line in your question is only 285 characters long, so your program will easily read it as a single line.
You can try changing the length of your array to see what happens when an input line is too long to fit:
char box[255];
...
fgets(box, sizeof box, fp);
Note that using sizeof box rather than repeating the number means the call won't get out of sync with the array size.
It only stops at the newline character \n or at n-1 characters. There is no newline character other than \n.
As you set the limit for your buffer and the amount fgets can read to 5000, it can easily read all the characters in your file and print them.
There is no line length limit in ISO C (ISO/IEC 9899), whether one is imposed by your book or not. Your book is probably outdated.

Sprintf function + order arguments [duplicate]

This question already has answers here:
Can the input and output strings to sprintf() be the same?
(2 answers)
Closed 7 years ago.
I have two string ta and tb with certain value, then I use the function sprintf to concatenate the two both in the variable ta, when I write
sprintf(ta,"%s+%s",ta,tb);
I get the string 1+2. but I need store in ta the string 2+1 then I trying
sprintf(ta,"%s+%s",tb,ta);
but I get the string 2+2+2+2+. I don't understand why happens that, Could you help me please?. Below the complete code
int main() {
char ta[5];
char tb[5];
sprintf(ta,"%d",1);
sprintf(tb,"%d",2);
sprintf(ta,"%s+%s",ta,tb);
//sprintf(ta,"%s+%s",tb,ta); uncomment for the second case
printf("taid:%s",ta);
}
sprintf(ta,"%s+%s",ta,tb);
sprintf(ta,"%s+%s",tb,ta);
Both lines of calling sprintf have undefined behavior. You are trying to copy ta to ta itself.
C11 §7.21.6.6 The sprintf function
The sprintf function is equivalent to fprintf, except that the output is written into an array (specified by the argument s) rather than to a stream. A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined.

fgets to include text after newline [duplicate]

This question already has answers here:
Correct way to read a text file into a buffer in C? [duplicate]
(8 answers)
Closed 7 years ago.
I want to make an array of characters and store the whole input in it(even if the input contains "\n" at some point. When i use:
char vhod[50];
fgets(vhod, sizeof(vhod), stdin);
it stores the input UNTIL the first newline. How to get the whole text in this array(including the text after the new line).
Example:
if my text is:
Hello I need new keyboard.
This is not good.
my array will only contain "Hello I need new keyboard.". I want to be able to read everything till the end of input a < input-1
I cannot use FILE open/close/read functions since it is input from keyboard.
While fgets() is designed to read up to a '\n' character or the specified number of bytes, you can use fread()1 instead, like this
size_t count = fread(vhod, 1, sizeof(vhod), stdin);
and count will contain the number of items read, which in this case is the same as the number of bytes since you are providing size 1 i.e. sizeof(char).
Note however that you must be very careful to add a terminating '\0' if you are going to use any function that assumes a terminating '\0'.
1Read the manual for more information.

Is the gets() string function in C considered a bad practice? [duplicate]

This question already has answers here:
Why is the gets function so dangerous that it should not be used?
(13 answers)
Closed 6 years ago.
was reading the Head first C book and stumbled across the author saying gets() to be a bad practice
gets() is a function that’s
been around for a long time.
But all you really need to know
is that you really shouldn’t
use it.
why is it considered a bad practice?
Consider
#include<stdio.h>
int main()
{
char buffer[100];
gets(buffer);
printf("The input is %s",buffer);
}
When user types input of length within 99 then there is no problem. But when user types more than 99 characters it tries to write into memory it doesn't own.
The worst thing is it causes abnormal behaviour and the program terminates without any information which leaves user baffled about the current situation
An alternative way is to use char *fgets(char *s, int size, FILE *stream); function
Update: As pointed by #pmg : gets() removes newline while fgets() retains the new line
gets is prone to buffer overruns (i.e. memory corruption etc).
fgets over comes this by having passing in the size of the buffer

How to allocate a memory for unknown string length in c [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to dynamically allocate memory space for a string and get that string from user?
I have a file. while reading line by line from a file, length of the string is unknown so how to allocate memory for unknown length string in an efficient way.
note:-
each line in a file is seperated by "\n".
programming language - c
The general pattern for doing this is
Allocate a buffer with malloc of a specified size.
Attempt to read into that buffer until you run out of space
Use realloc to double the size of the buffer and continue reading
Continue with this pattern until the file is completely read
One way is to find out the file size via system calls (fstat if I remember correctly). That's not particularly good if the file is very large, as it might potentially not fit in memory.
Another way is to read line by line (or in chunks of n bytes) until you hit the end of file character. See:
http://pubs.opengroup.org/onlinepubs/000095399/functions/fread.html
You can use malloc, fgets and realloc.
Start with a malloc of fixed size. Perhaps 64 bytes.
Then fgets the size of your string. Check if the end of your string has a \n. If not, realloc the string to double the size. Now fgets some more and repeat until your string ends with a newline or you reach the end of the file.

Resources