Read a specific word from text file [closed] - c

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.

Related

Program to Replace a string of one or more blanks with a single blank. No library functions can be used. This is not EOF version [closed]

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 4 years ago.
Improve this question
/* ============================================================================
Name : 3_1-9.c
Author : Arvind Bakshi
Version :
Copyright : AbcoolCoding
Description : Program to Replace a string of one or more blanks with a single blank
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#define NOBLANK 'a'
int main(void) {
setbuf(stdout,NULL);
char string[30],out[30];
int i;
puts("Enter a String of size < 30");
fgets(string,sizeof(string),stdin);
for(i=0; string[i]; i++){
if(string[i]!=' ')
out[i]=string[i];
}
puts(out);
return EXIT_SUCCESS;
}
The above program fails to shrink down more than one blanks in a string. Note that no library functions except stdio.h are allowed. You can find the code at -https://github.com/abcool/C_training/blob/Chapter-1/01_1.5.3_1-9.c
Here is my observation from the code you mentioned, firstly here
fgets(string,sizeof(string),stdin);
fgets() stored the \n char at end of buffer if read. From the manual page of 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.
you need to remove the trailing \n char. One way is to use strcspn(). For e.g
string[strcspn(string, "\n")] = 0;
Secondly, here
out[i]=string[i];
for out array you should use different index rather than i. For e.g
int count = 0;
for(i=0; string[i]; i++){
if(string[i]!=' ')
out[count++]=string[i]; /* use count for out */
}
And then put the \0 char at the end of out.
out[count] = '\0';
for(i=0; string[i]; i++){
if(string[i]!=' ')
out[i]=string[i];
}
Because out can be smaller than string you need to have a separate index for each, the index in out must progress only when you put a new character in it
So currently you print non initialized characters, that explains the '+' and probably a null character just after stopping the print.
Replace a string of one or more blanks with a single blank : your program try to remove all the spaces, not to replace consecutive spaces by only one
Do not forget to put the ending null char in out at the end

C reading from file: Reading only first char of line [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 6 years ago.
Improve this question
I have to get node ids from DIMES ASNodes.csv (http://netdimes.org/new/?q=node/65) files.
File looks like this:
6067,UNKNOWN,2007-02-03 10:03:53.0,2007-01-02 02:54:13.0,12,6,0
29287,UNKNOWN,2007-02-03 21:11:07.0,2007-01-02 07:33:35.0,1,0,0
...
So far I came up with this code, but it doesn't work quite right. Althought it prints out all the numbers I needed, it also prints out the node id twice and sometimes prints zeroes in between. Thanks for any ideas
void loadNodes(const char* filename)
{
FILE* nodes = fopen(filename, "r");
unsigned int id = 0;
char line[64];
while (fgets(line, sizeof(line), nodes) != NULL) {
sscanf(line, "%u%*[^\n]", &id);
printf("id = %u\n", id);
}
fclose(nodes);
}
output
I think the trouble is that your lines have 63 characters plus a newline, which means that the fgets() reads up to, but not including, the newline (and you process that and get the correct number), then the next fgets() reads the newline that was left behind on the previous input (and you process that — it is surprising that you get zeros rather than a repeat of the previous number).
Here's your code converted into an MCVE (How to create a Minimal, Complete, and Verifiable Example?) main() program that reads from standard input (which saves me from having to validate, open and close files):
#include <stdio.h>
int main(void)
{
unsigned id = 0;
char line[64];
while (fgets(line, sizeof(line), stdin) != NULL)
{
printf("Line: [%s]\n", line);
sscanf(line,"%u", &id);
printf("id = %u\n", id);
}
return 0;
}
Note the diagnostic printing of the line just read. The code should really check the return value from sscanf(). (There was no virtue in skipping the trailing debris, so I removed that from the format string.)
Given the data file (data):
6067,UNKNOWN,2007-02-03 10:03:53.0,2007-01-02 02:54:13.0,12,6,0
29287,UNKNOWN,2007-02-03 21:11:07.0,2007-01-02 07:33:35.0,1,0,0
The output I get from so.37103830 < data is:
Line: [6067,UNKNOWN,2007-02-03 10:03:53.0,2007-01-02 02:54:13.0,12,6,0]
id = 6067
Line: [
]
id = 6067
Line: [29287,UNKNOWN,2007-02-03 21:11:07.0,2007-01-02 07:33:35.0,1,0,0]
id = 29287
Line: [
]
id = 29287
Avoiding the problem
The simplest fix is to use a longer buffer length; I normally use 4096 when I don't care about what happens if a really long line is read, but you might decide that 128 or 256 is sufficient.
Otherwise, I use POSIX getline() which will read arbitrarily long lines (subject to not running out of memory).
With a longer line length, I get the output:
Line: [6067,UNKNOWN,2007-02-03 10:03:53.0,2007-01-02 02:54:13.0,12,6,0
]
id = 6067
Line: [29287,UNKNOWN,2007-02-03 21:11:07.0,2007-01-02 07:33:35.0,1,0,0
]
id = 29287
Assuming you only need the first column from the file (since you mention node ids), you could use:
unsigned int node_id;
char str[100];
while(scanf("%u,%[^\n]",&node_id, str) == 2) {
printf("%u\n",node_id);
}
Demo

How can I read and process this kind of file [closed]

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

Text file with different data types into structure array [closed]

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 9 years ago.
Improve this question
I have to parse a text file with 3 different data types. I want it to be saved in a structure array with three members. My text file look like this:
A B 45.78965
A C 35.46731
B C 46.78695
The program that I'm reading it with is the following and it does not work.
What am I doing wrong?
#include <stdio.h>
struct gra {
char from;
char to;
double w;
};
int main ()
{
FILE *fp = fopen("graph.txt", "r");
int i = 0;
while (!feof(fp)) {
fscanf(fp, "%[^\t]", &graph[i].from, &graph[i].to, &graph[i].w);
i++;
}
fclose(fp);
}
One of your problems is that you're reading using %[^\t], which reads strings, and store the result to variables that are not character arrays (two characters and a double).
Although it's not clear from your question, it seems that the lines of your input contain two characters and one real number separated by one tab character. If that is so, you should use the following fscanf to read them:
fscanf(fp, "%c\t%c\t%lf\n", &graph[i].from, &graph[i].to, &graph[i].w);
If you are not sure what exactly separates your fields and you want to allow any amount of white space in between and also extra white space in the beginning and end of the line, then use:
fscanf(fp, " %c %c%lf\n", &graph[i].from, &graph[i].to, &graph[i].w);
that is, use an extra space in the format before each "%c" to explicitly skip white space.
Your code has also a couple of other problems:
You are using feof to check for end of file. This will usually not work well if you're not reading the file character by character. Instead, you should check if your fscanf returned 3, that is, if it successfully read the three things that you wanted it to read.
You are missing a definition of array graph.
I'm adding the complete code that I'd write for doing the parsing:
#include"stdio.h"
#define MAX 100
struct {
char from, to;
double w;
} graph[MAX];
int main ()
{
FILE *fp = fopen("graph.txt", "rt");
for (int i=0; i<MAX; i++)
if (fscanf(fp, " %c %c%lf\n", &graph[i].from, &graph[i].to, &graph[i].w) < 3)
break;
fclose(fp);
return 0;
}

Text file with different data types into structure arrays [duplicate]

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 9 years ago.
Improve this question
I have to parse a text file with 3 different data types. I want it to be saved in a structure array with three members. My text file look like this:
A B 45.78965
A C 35.46731
B C 46.78695
The program that I'm reading it with is the following and it does not work.
What am I doing wrong?
#include <stdio.h>
struct gra {
char from;
char to;
double w;
};
int main ()
{
FILE *fp = fopen("graph.txt", "r");
int i = 0;
while (!feof(fp)) {
fscanf(fp, "%[^\t]", &graph[i].from, &graph[i].to, &graph[i].w);
i++;
}
fclose(fp);
}
One of your problems is that you're reading using %[^\t], which reads strings, and store the result to variables that are not character arrays (two characters and a double).
Although it's not clear from your question, it seems that the lines of your input contain two characters and one real number separated by one tab character. If that is so, you should use the following fscanf to read them:
fscanf(fp, "%c\t%c\t%lf\n", &graph[i].from, &graph[i].to, &graph[i].w);
If you are not sure what exactly separates your fields and you want to allow any amount of white space in between and also extra white space in the beginning and end of the line, then use:
fscanf(fp, " %c %c%lf\n", &graph[i].from, &graph[i].to, &graph[i].w);
that is, use an extra space in the format before each "%c" to explicitly skip white space.
Your code has also a couple of other problems:
You are using feof to check for end of file. This will usually not work well if you're not reading the file character by character. Instead, you should check if your fscanf returned 3, that is, if it successfully read the three things that you wanted it to read.
You are missing a definition of array graph.
I'm adding the complete code that I'd write for doing the parsing:
#include"stdio.h"
#define MAX 100
struct {
char from, to;
double w;
} graph[MAX];
int main ()
{
FILE *fp = fopen("graph.txt", "rt");
for (int i=0; i<MAX; i++)
if (fscanf(fp, " %c %c%lf\n", &graph[i].from, &graph[i].to, &graph[i].w) < 3)
break;
fclose(fp);
return 0;
}

Resources