Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
And I want it to print to output as is. Curently I am using this code
#include <stdio.h>
#include <ctype.h>
#define BUFFER_SIZE 2000
int main(void)
{
char buffer[BUFFER_SIZE];
while(fgets (buffer, BUFFER_SIZE, stdin) !=NULL)
{
printf("%s",buffer);
}
return 0;
}
Then I want the program to be able to skip html tags in the original text but I don't know exactly how to work around that.
You should use getline(3) (at least on Posix compliant systems). Your fgets based code won't work with very long lines (because a very long line would be "truncated": all of it would be read, but only BUFFER_SIZE characters would have been copied, and the rest of the line ignored).
You could code
char* linebuf=NULL;
size_t linesize=0;
while (!feof(stdin)) {
ssize_t linelen = getline(&linebuf, &linesize, stdin);
if (linelen<0) { perror("getline"); exit(EXIT_FAILURE); };
fputs(linebuf, stdout);
}
In the above code, the linebuf will (unless failure) be grown to the widest line size. You should free(linebuf) after that loop...
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
FILE *filePointer ;
char dataToBeRead[50];
filePointer = fopen("input.txt", "r") ;
while( fgets ( dataToBeRead, 50, filePointer ) != NULL )
{
printf( "%s" , dataToBeRead ) ;
}
fclose(filePointer) ;
}
And this is the text file enter image description here. I want to take the word in the middle of each line and print it.
You can use
strtok(str, ",")
strtok(NULL, ",")
printf("%s\n", str);
This is not thread-safe or re-entrant but you're unlikely to care about that for this exercise.
If this is too fancy (I assume this is a student exercise and a simpler version may be desired) try stepping through the string character-by-character, counting commas and using putchar during the appropriate section.
As with many tasks in C, there are lots of ways to do this one. One suggestion could be to use the strstr() and snprintf() functions to help find the beginning of the search word then truncate the rest of line to include only the word of interest: (your code modified to use this approach)
while( fgets ( dataToBeRead, 50, filePointer ) != NULL )
{
char *temp = strstr(dataToBeRead, "SearchTerm");
if(temp != NULL)
{
char found[50]={0};
snprintf(found, strlen("searchTerm"), temp)
printf( "%s" , found) ;
}
...
Another way, (simpler, but perhaps not as satisfying) simply test the input buffer for existence of the search term using strstr() (as the above example does), but if strstr() does not return NULL, then simply print out the given search term without bothering to parse its twin from out of the line buffer.
Aside: Magic numbers (Such as 50 in your example: char dataToBeRead[50]; are not as useful as human readable and understandable variables and/or #define values, eg:
#define MAX_FILE_LINE_LEN 50
Then in your code, everywhere 50 would be used, replace it with MAX_FILE_LINE_LEN
And, while on the topic, use a more reasonable length than 50. At least 80, but 260 would not be too big for most systems either.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Was talking to a colleague today on one-spot errors - I.e. errors (or at least patterns that should ring an alarm bell) in code that a decent programmer should be able to spot at a single glance like
x = malloc (strlen(y));
while (!feof (f)) {
...
}
char *f(){
char x[100];
...
return x;
}
Who has similar snippets of such patterns? I would suggest anyone who has been on SO for a while will have his personal favourites of those
char *buf;
scanf("%s", buf);
This is wrong, because no memory has been allocated for buf.
char buf[100];
scanf("%s", &buf);
This is wrong, because scanf expects a char *, not a char (*)[n].
char c;
while ((c = getchar()) != EOF)
putchar(c);
This is wrong, because EOF does not fit in the range of a char. Use int instead.
fflush(stdin);
fflush is undefined for input streams, like stdin, albeit this is implemented as an extension in some compilers, like Microsoft C.
#define IN 0;
Do not put semicolons at the end of a #define.
blk = realloc(blk, n);
If realloc fails, any contents in blk will be lost, because realloc will return NULL. To solve the problem, copy the return value into a temporary and only if the temporary is not NULL, copy to the final destination.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm making a RPG game in C, and I need to read from a single file. Having multiple files is very tedious. Like "health.dat", "energy.dat", "money.dat" etc. I want to put them into one "data.dat", is this possible?
I just want to read specific line from a file
If line 1 has "number 1", then it should go to the "a" variable, line 2 should go to the "b" variable, etc.
Many thanks.
It is possible.
you can use the array of pointers in the fgets function.
char *fgets(char *s, int size + 1, FILE *stream);
fgets (array,size + 1,stream);
where array is *array[size];
You can achieve what you describe using the fgets function as follows:
#include <stdio.h>
#include <stdlib.h>
const int MAX_LENGTH = 256;
int main (void)
{
// Open the file
FILE* file = fopen ("data.dat", "r");
// Read the lines
char a[MAX_LENGTH];
fgets (a, MAX_LENGTH - 1, file);
char b[MAX_LENGTH];
fgets (b, MAX_LENGTH - 1, file);
// ...
// Close the file
fclose (file);
return EXIT_SUCCESS;
}
Set the MAX_LENGTH variable to the maximum expected length of a line in your file. You should also test fopen and fgets for returning NULL, as both are error conditions.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I 12 0
I 9 1
I 26 0
I 25 2
B 26
P 0
R 25
A
So, what I need to do is read a file containing these characters/numbers and whenever I encounter a letter, I call a function to process whatever comes after the letter (aka the numbers).
For example:
When reading "I" I have to call the function to INSERT a certain number in a certain level of a Skip List; or when reading B, I need to search for a specific number in the Skip List, etc.
Problem is I'm really bad at reading from a file, can you guys enlighten me?
You can do this with file operations in c,
i am just giving you hints,
FILE *pFilePtr; // file pointer(handle of file)
pFilePtr = fopen(argv[1],"r");
//define buffer to store data read line by line data
char buf[32]={0};
//Now you can run a while loop to read entire file
with fread() to get whole first line(until '\n')
while(!feof(pFilePtr))
{
if(NULL != fgets(buf,32,pFilePtr))
// perform string operation on buffer to extract letters and digits
// and according to that call functions you need
}
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fptr;
char mystring[20];
int number;
fptr = fopen("Input.txt", "r");
while(fscanf(fptr , "%s %d", mystring, &number) != EOF) {
printf("%s %d\n", mystring, number);
if(strcmp(mystring, "I") == 0) {
printf("Implement the reqd function here\n");
}
}
}
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 7 years ago.
Improve this question
This code will not run. Can somebody tell me why?
#include <stdio.h>
#include <string.h>
main (){
char user[7];
printf("Username\n");
scanf("%s",user);
if(user == 'admin'){
printf("Hello World");
}else{
printf("Bad");
}
return(0);
}
This is a working example. You need to use strcmp to compare strings. strcmp() returns 0, if the strings are equal.
If the max input length is known, then you should also use length specifier in scanf or one of the suggestion listed here, to prevent a buffer overflow.
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv)
{
char user[7];
printf("Username:\n");
scanf("%6s", user);
if(!strcmp(user, "admin"))
{
printf("Hello World");
}
else
{
printf("Bad");
}
return 0;
}
This is not working because you are comparing two strings the wrong way. You need to use strcmp. Check this answer to see what strcmp returns in C.
To make your program work, change the line
if (user == 'admin')
to
if (strcmp (user, "admin") == 0)
Also, using scanf might be a bit dangerous, in rare cases. I prefer using fgets for strings. To use fgets, do:
fgets (user, sizeof (user), stdin);