I've read in and stored a data file that I am processing into an array of char arrays, one char array for each line in the file and I now want to process the individual lines. I'm not however sure how to do this.
I read each line in like so:
/* Read the whole file into an array */
char read_lines[FILE_LENGTH][FILE_WIDTH];
for(i=0;i<FILE_LENGTH;i++) {
fscanf(data_file, "%[^\n]", read_lines[i]);
fscanf(data_file, "%[\n]", dump);
}
I need to read the data in each line which is formatted as %d\t%d\t%d\t%d\t%d and I'm not really sure how to read a specific variable into a scanf function. I know that fscanf() reads from a file and scanf() reads from user input, is there a function that reads from a variable?
I come from a python background and in python, I would just use the following code:
read_lines = open('file.txt').readlines()
for line in lines:
i = lines.index(line)
first[i], second[i], third[i], forth[i], fifth[i] = line.split('\t')
I really cannot see how to do the equivalent in C. I've done a fair bit of research but I couldn't find anything useful. Any help would be appreciated!
Thanks!
Perhaps check out sscanf. It is just like it's cousin scanf and fscanf but takes a string instead. Here is a snip from the above link.
The sscanf function accepts a string from which to read input, then, in a manner similar to printf and related functions, it accepts a template string and a series of related arguments. It tries to match the template string to the string from which it is reading input, using conversion specifier like those of printf.
You can use the strtok function [read the manpage] to split a string
e.g. http://www.gnu.org/s/libc/manual/html_node/Finding-Tokens-in-a-String.html
Related
My goal here is to read through a text file that has to follow these formatting regulations:
No spaces/tabs between characters
Characters must be either non-negative integer or new line character (no letters/symbols)
I can only use functions given in stdlib.h and stdio.h
I am thinking of reading through the file character by character using the fgetc() function, but I can't think of a way that tests whether or not the character is a new line character (isn't a new line char /n, which would be two chars together which would ruin the idea of going char by char?).
Following this train of thought I was thinking that using getline(), which would negate the necessity of checking if a char is a new line character, would be easier (am I right in thinking this or would this not negate such a requirement?). Yet if I were to do this what would be the easiest way to traverse through the char string that this would produce in order to still check each individual character?
Also, if someone could think of an easier route as to checking for the format of a file using the given libraries that would be much appreciated.
If you use getline it will retain the newline character so you'll still have to check for it.
If you can use any of the standard C library then you can use isdigit(...) from ctypes.h
It returns non-zero if the input character is a digit.
If you use the getline function the input would be written into the buffer that you pass as the first argument. It will append a null terminal character to this buffer so you can walk through it as so:
for(char* s = buffer; *s; s++)
/* test *s */
I have a text file full of points of the following format on different lines
LONG,LONG
i can successfully read each line and print it out, but I how can I parse the string in C such that I get each long of each point on its own?
Thanks!
if you have the line already, it's easiest to use sscanf() to do this:
long a, b;
if(sscanf(line, "%ld,%ld", &a, &b) == 2)
{
/* Successfully parsed two long integers, now store them somewhere I guess. */
}
Note that it's a good idea to check the return value of sscanf(), this protects you from wrongly accepting illegal data and getting undefined results.
You can do it in multiple steps too if you need more control, as #dasblinkenlights suggested. You can use strtol() to parse the first number from the start of the line, then if that succeeds look for the comma, and then parse the second number. It can be faster than sscanf(), but I wouldn't expect too much for something this simple.
There are many solutions to this.
One is to read the line, read the first long with strtol find the position of the comma that follows with strchr, and read the second number from there.
Another solution would be to read the line, and pass it to sscanf function with the format that accepts two comma-separated LONGs.
Use the string variant of scanf() if you say you've already got the line:
char* line;
long long1;
long long2;
sscanf(line, "%ld,%ld", &long1, &long2);
Indeed as #unwind suggests in his +1 answer, it's a very good idea to check the return value of scant(), which is the number of successfully read values.
I have to read a csv file using fscanf function (I cant use any other function like strtok_s to parse the line) and im having the following problem.
Here is the code:
fp1 = fopen (argv [1],"r");
var = fscanf (fp1,"%d,%d,%[^,]s,%[^,]s",&aux.points,%aux.titles,aux.name,aux.nation);
I'm trying to print each parameter in the screen. There is no problem with the integers and even with the first string (name) but nothing is stored in the next string (nation).
I assume that the first %[^,]s is stopping the execution of the whole fscanf function so the next string is never read. Any idea? I have tried everything but this is just not working.
Try this as the string:
"%d,%d,%[^,],%[^,]"
I eliminated the "s" because [...] acts as the specifier.
Think of the [...] as a super s.
I am new to C programming, so I am having difficulties with the problem below.
I have a text file inp.txt which contains information like the following:
400;499;FIRST;
500;599;SECOND;
670;679;THIRD;
I need to type a number and my program needs to compare it with numbers from the inp.txt file.
For example, if I type 450, it's between 400 and 499, so I need write to the word FIRST to the file out.txt
I have no idea how to convert a character array to an int.
I think you'll want these general steps in your program (but I'll leave it to you to figure out how you want to do it exactly)
Load each of the ranges and the text "FIRST", "SECOND", etc. from the file inp.txt, into an array, or several arrays, or similar. As I said in the comment above, fscanf might be handy. This page describes how to use it - the page is about C++, but using it in C should be the same http://www.cplusplus.com/reference/clibrary/cstdio/fscanf/. Roughly speaking, the idea is that you give fscanf a format specifier for what you want to extract from a line in a file, and it puts the bits it finds into the variables you specify)
Prompt the user to enter a number.
Look through the array(s) to work out which range the number fits into, and therefore which text to output
Edit: I'll put some more detail in, as asker requested. This is still a kind of skeleton to give you some ideas.
Use the fopen function, something like this (declare a pointer FILE* input_file):
input_file = fopen("c:\\test\\inp.txt", "r") /* "r" opens inp.txt for reading */
Then, it's good to check that the file was successfully opened, by checking if input_file == NULL.
Then use fscanf to read details from one line of the file. Loop through the lines of the file until you've read the whole thing. You give fscanf pointers to the variables you want it to put the information from each line of the file into. (It's a bit like a printf formatting specifier in reverse).
So, you could declare int range_start, range_end, and char range_name[20]. (To make things simple, let's assume that all the words are at most 20 characters long. This might not be a good plan in the long-run though).
while (!feof(input_file)) { /* check for end-of-file */
if(fscanf(input_file, "%d;%d;%s", &range_start, &range_end, range_name) != 3) {
break; /* Something weird happened on this line, so let's give up */
else {
printf("I got the following numbers: %d, %d, %s\n", range_start, range_end, range_name);
}
}
Hopefully that gives you a few ideas. I've tried running this code and it did seem to work. However, worth saying that fscanf has some drawbacks (see e.g. http://mrx.net/c/readfunctions.html), so another approach is to use fgets to get each line (the advantage of fgets is that you get to specify a maximum number of characters to read, so there's no danger of overrunning a string buffer length) and then sscanf to read from the string into your integer variables. I haven't tried this way though.
I am wondering if there is a function I could use in the standard libary. Do I need another library (BTW, I am developing for unix).
See the scanf() function in stdio.h. It takes a format specifier like printf() and pointers to the variables to store the user input in
Use scanf()
Format: int scanf ( const char * format, ... );
Read formatted data from stdin.
Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format tag within the format string.
Example:
#include <stdio.h>
int main(void)
{
int n;
printf("Enter the value to be stored in n: ");
scanf("%d",&n);
printf("n= %d",n);
}
However have a look at this.
You seems quite new to C so let me add a little something to Prasoon answer, which is quite correct and complete, but maybe hard to understand for a beginner.
When using scanf( const char * format, ... ); in his exemple, Prasoon use :
scanf("%d",&n);
When using this, the "%d" indicate you're going to read an integer (See wikipedia for complete format list ).
The second argument (note that the ... indicates you can send any number of arguments) indicate the address of the variable in which you are gonna stock user entry.
'Tis interesting - two answers so far both suggest scanf(); I wouldn't.
When everything goes right, scanf() is OK. When things go wrong, recovery tends to be hard.
I would normally use fgets() to read the user information for one line into a buffer (character array) first. I would then use sscanf() to collect information from the buffer into the target variables. The big advantage is that if the user types '12Z' when you wanted them to type two numbers, you can tell them what you saw and why it is not what you wanted much better. With scanf(), you can't do that.