If I do :
int main(){
const int LENGTH_LINE = 100;
char line[LENGTH_LINE];
int len;
FILE* fp = fopen(file.txt,"r");
fgets(line,LENGTH_LINE,fp);
len = strlen(line);
if(line[len-1] == '\n')
printf("I've a line");
//This work if the line have \n , but if the end line of the text dont have \n how can do it?
}
I need to know if I take a whole line with fgets because I got a delimiter.
According to http://en.cppreference.com/w/c/io/fgets
Reads at most count - 1 characters from the given file stream and stores them in str.
Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.
So, once fgets returns, there are 3 possibilities
LENGTH_LINE was reached
We got a newline
EOF was reached.
I'm assuming you have a line in cases 2 and 3.
In this case the detection condition is :
line[len-1] == '\n' || feof(fp)
Check for the newline character:
size_t len = 0;
// ... your code using fgets
len = strlen(line);
if ((len > 0) && (line[len - 1] == '\n'))
// your input contains the newline
After the fgets call, your line may not have a newline at the end if:
The character limit was reached before a newline was scanned - in your case this is LENGTH_LINE.
The end-of-file (EOF) was reached before a newline.
There was a read error, but in case of an error consider the contents of line unusable.
You should be looking at the return value from fgets so that you'll be able to handle the EOF: fgets returns NULL upon end-of-file or a read error. You can use feof to check for the end-of-file.
If you check feof, and know that you're at the end of your input with no fgets errors, then even without a newline character on the final line you'll know that you've read the entire line.
If for some reason you must have a newline character terminating each line, you can add it yourself:
// you've checked for EOF and know this is your final line:
len = strlen(line);
if (line[len-1] == '\n')
printf("I've a line");
else if ((len + 1) < LENGTH_LINE)
{
line[len] = '\n';
line[len + 1] = '\0';
}
else
// no room in your line buffer for an add'l character
Use like this
while(fgets(line,LENGTH_LINE,fp)!=EOF)
// your code here
Why not just use fgetc instead? That way you can just keep scanning until you get to the end of the line so you don't have to check if you have it.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char line[100];
int ch, i = 0;
FILE* fp = fopen(file.txt,"r");
while(ch != '\n' || ch != '\r' || ch != EOF) //or ch != delimiter
{
ch = fgetc(fp);
line[i] = ch;
i++;
}
line[i] = '\n';
line[i+1] = 0x00;
return 0;
}
In that example I just look for a new line, return, or EOF character but you can really make it look for anything you like (e.g. your delimiter). So if your delimiter was q you would just do
while(ch != 'q')...
Related
I am facing some problems while understanding the following code.
It is a program to read Strings from keyboard if the length of the String is lesser than the specified size (i.e 'n' here).
If the length of a string is larger than the specified size, the remaining characters on the line will be discarded.
More specifically, I want to know what is happening inside the buffer and how getchar() is reading the data and not storing it in the buffer.
char * s_gets(char * st, int n)
{
char * ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val) // i.e., ret_val != NULL
{
while (st[i] != '\n' && st[i] != '\0')
i++;
if (st[i] == '\n')
st[i] = '\0';
else // must have words[i] == '\0'
while (getchar() != '\n')
continue;
}
return ret_val;
}
The code is slightly flawed, but does more or less the job outlined. It uses fgets() to do a lot of the work. That reads up to n - 1 characters from standard input. When it returns, there are a few possibilities:
(EOF) Nothing was available to be read. Nothing has been put in the buffer, but fgets() returned NULL.
(Normal) A line has been read and fitted into the buffer st. The buffer includes the newline.
(Overlong) Part of a line has been read, but the input did not find a newline.
(EOF without newline) Some data was read, but there wasn't a newline before EOF was detected.
Case 1 is simplest: the code returns NULL. Case 2 is handled by scanning the string that's read to find the newline. If the newline is found, it is overwritten with a null byte. Case 3 is handled at the same time; if the value found isn't a newline, it must be the null byte. The code drops into a loop that reads more characters until a newline is read. Case 4 is similar to case 3 in effect, but the code in the loop mishandles this — it doesn't detect and handle EOF, so the code would fall into an indefinite loop. That's a bug that needs to be fixed.
The getchar() loop doesn't assign anything to the buffer st — it makes no changes to st. That continues to contain a null terminated string as read by fgets(). The getchar() loop reads and discards any characters left on the line that was read that did not fit into the buffer.
The code should be:
char *s_gets(char *st, int n)
{
assert(n > 1 && st != NULL);
char *ret_val = fgets(st, n, stdin);
if (ret_val != NULL)
{
int i = 0;
while (st[i] != '\n' && st[i] != '\0')
i++;
if (st[i] == '\n')
st[i] = '\0';
else
{
int c;
while ((c = getchar()) != EOF && c != '\n')
continue;
}
}
return ret_val;
}
The return value of NULL or the original string is the same as fgets() uses, but it isn't the most useful return value. It would be more useful, most often, if the code returned the length of the string that it read, or returned EOF if it encountered EOF (or a read error). The information is readily available — in the variable i.
I am trying to switching my use of getchar to fgets but, when using getchar, the entire code does not work.
//fgets(line, sizeof(line), stdin);
while(fgets(line, sizeof(line), stdin))
{
portNum[sizeof(line)] = (char)line;
}
while((c = getchar()) != '\n')
{
portNum[num++] = c;
}
portNum[num] = '\0';
How can I make equal for those two functions to work properly?
You usage of fgets is wrong.
fgets Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
In your case fgets will read all the characters until newline is encountered.
Also, the parameters usage is wrong.
char * fgets ( char * str, int num, FILE * stream );
str => Pointer to an array of chars where the string read is copied.
num => Maximum number of characters to be copied into str (including the
terminating null-character).
stream => Pointer to a FILE object that identifies an input stream.
stdin can be used as argument to read from the standard input.
Refer to the fgets documentation for more information.
fgets man page
OP's fgets() usage is unclear and portNum[sizeof(line)] = (char)line; is certainly in error.
Instead: how to make the below getchar() code more fgets()-like:
// assumed missing code
#define N 100
int c;
char portNum[N];
size_t num = 0;
// size and EOF detection added (which should have been there)
while(num + 1 < sizeof portnum && (c = getchar()) != '\n' && c != EOF) {
portNum[num++] = c;
}
portNum[num] = '\0';
// assumed missing code
if (c == EOF && num == 0) Handle_EndOfFile_or_InputError();
else ...
This can be replaced with fgets() code
#define N 100
char portNum[N+1]; // 1 larger for the \n
if (fgets(portNum, sizeof portNum, stdin)) {
// lop off potential trailing \n
portNum[strcspn(portNum, "\n")] = '\0';
...
} else {
Handle_EndOfFile_or_InputError();
}
I get very unexpected output from quite simple code
char ch = getchar(), word[100], *p = word;
while (ch != '\n') {
*(p++) = ch;
ch = getchar();
}
puts(word);
output of any 17 character input is appended by "time" like
12345678901234567time
if exceeds "time" is overwritten like
1234567890123456789me
Am I doing something wrong?
puts expects a pointer to string. And a string needs to have a terminating null character - \0 - to signify where the string ends.
But in your case, you did not write the \0 at the end to signify that the string ends there.
You need to do:
char ch = getchar(), word[100], *p = word;
/* Also check that you are not writing more than 100 chars */
int i = 1;
while(ch != '\n' && i++ < 100){
*(p++) = ch;
ch = getchar();
}
*p = '\0'; /* write the terminaring null character */
puts(word);
Before, when you were not writing the terminating null character you could not expect anything determinate to print. It could also have been 12345678901234567AnyOtherWord or something.
There are multiple issues in your code:
You do not null terminate the string you pass to puts(), invoking undefined behavior... in your case, whatever characters happen to be present in word after the last one read from stdin are printed after these and until (hopefully) a '\0' byte is finally found in memory.
You read a byte from stdin into a char variable: this does not allow you to check for EOF, and indeed you do not.
If you read a long line, you will write bytes beyond the end if the word array, invoking undefined behavior. If the end of file is encountered before a '\n' is read from stdin, you will definitely write beyond the end of the buffer... Try for example giving an empty file as input for your program.
Here is a corrected version:
char word[100];
char *p = word;
int ch;
while ((ch = getchar()) != EOF && ch != '\n') {
/* check for long line: in this case, we truncate the line */
if (p < word + sizeof(word) - 1) {
*p++ = ch;
}
}
*p = '\0';
puts(word);
this is my code below. What it does is not the issue. The issue is that once it is run, I put in my input and if its too small it will ask for input again on the second line which appears to have no affect the flow of my program. If I fill the buffer (which I'm assuming 100 or more) then I am not asked for a second prompt.
#include <stdio.h>
#include <string.h>
int main()
{
int ch;
char x[3];
char *word, string1[100];
x[0]='y';
while(x[0]=='y'||x[0]=='Y')
{
fgets(string1, 100, stdin);
while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
printf("The string is: %s", string1);
word = strtok(string1, " ");
while(word != NULL)
{
printf("%s\n", word);
word = strtok(NULL, " ");
}
printf("Run Again?(y/n):");
fgets(x, 2, stdin);
while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
}
return 0;
}
EDIT:
I have replaced,
fgets(string1, 100, stdin);
while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
With,
fgets(string1, 100, stdin);
if (string1[98] != '\n' && string1[99] == '\0')
{
while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
}
From the man page:
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops
after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the
last character in the buffer.
fgets will place all input, up to 99 chars, into string1. If you input 98 characters and hit enter (creating a 99th \n), then all 100 will be used as the last one is a \0 terminator.
Then you fall into that small while loop which does nothing but consume another line of input. If you input less than the max for your string, then input is halted while that loop waits for a \n.
If you input >98 characters, then the first 99 are saved to your input string, and the remainder along with that final \n are immediately run through that while loop, causing it to exit quickly enough that it may seem to be skipped.
I hope that helps. Unfortunately I can't comment and ask for clarification, so I'll say here that it's a little difficult to tell what exactly you want fixed or made clear.
The answer to your question is right here: man fgets
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
To know if fgets used the whole buffer, write some non-NUL byte into the end of the buffer. If, after calling fgets, that byte has been overwritten with a NUL, it means the buffer is full. If the character directly before it is not a newline, then there's more input still to be read.
buffer[size - 1] = 'a'; // any character that's not '\0'
fgets(buffer, size, stdin);
if (buffer[size - 1] == '\0' && buffer[size - 2] == '\n') {
// handle extra input
}
Alternatively, you could just read bytes one at a time using getchar.
I think you need this:
Note: x must be int if you want to compare it against EOF
int main()
{
int x;
char *word, string1[100];
do
{
fgets(string1, 100, stdin);
printf("The string is: %s", string1);
word = strtok(string1, " ");
while(word != NULL)
{
printf("%s\n", word);
word = strtok(NULL, " ");
}
printf("Run Again?(y/n):");
x = fgetc(stdin);
fgetc(stdin); // absorb `\n`
}
while( (x=='y'||x=='Y') && x != EOF) ;
return 0;
}
I know I can get the first character of a line of standard input by using getchar(), but I only want the first character of each line. Is there a function I can use to get rid of the rest of the string entered into standard input (if it is more than one character)? if not, what methodology should I consider using to get rid of the rest of the standard input line?
char buf[100];
while(fgets(buf,sizeof(buf),stdin) != NULL)
{
if(strlen(buf)>0)
buf[1] = '\0';
printf("%s",buf);
}
Read the whole line using fgets() and just nul terminate it after the first character.
#include <stdio.h>
int main(void)
{
int ch;
size_t len;
for (len = 0; 1; ) {
ch = getc(stdin);
if (ch == EOF) break;
if (!len++) putc(ch, stdout); /* the first character on a line */
if (ch == '\n') len = 0; /* the line has ended */
}
return 0;
}
Please note that the first character on a line can actually be a '\n' !!!
// Get the character you need
char c = getchar();
// Skip the rest
int a;
while((a = getchar()) != '\n' && a != EOF);
If you know how many lines you'll have, you can put it in a loop.