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

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

Related

Read a specific word from text file [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 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.

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

why in this piece of code, fgets returns null when it shouldn't? [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 concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I am coding a program that a piece of it is as below:
#define BUFFSIZE 2000
while( fgets(buff, BUFFSIZE - 1, fPtr) != NULL)
{
//how many words is read from the source file in the current line
int wordread = 0;
word = strtok(buff, punc);
//one word read
while( word != NULL)
{
//sorting
int k = 0;
while(strcmp(word, words[k]) < 0)
k++;
if(strcmp(word, words[k]))
{
last++;
for(int l = last; l >= 0; l--)
strcpy(words[l + 1],words[l]);
strcpy(words[wordread],word);
}
index[last][lineread]++;
wordread++;//go to next word
word = strtok(NULL, punc);
}
lineread++;//go to next line
}
but I understood that the compiler doesn't go inside the first while
while( fgets(buff, BUFFSIZE - 1, fPtr) != NULL)
I understood that this fgets returns NULL at first. but fPtr has an correct address and in the address there is a file of some data.
FILE *fPtr = fopen(argv[1], "r");
and the definition of buff is:
char buff[BUFFSIZE];
can anyone help? if the whole of the code is needed, tell me to write all of it.
The problem that the compiler didn't get into the first loop was the the file that it was supposed to read of, wasn't there. and It was returning NULL

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

Program to read input lines of any length in C [closed]

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...

Resources