fscanf function not working - scanf

I'm currently writing a program that reads numbers from sets of 2 numbers from a text file and prints them out. I'd like to use the numbers to determine a GCD later, but I have to be able to scan them from the file first. The text file looks like this:
24 72
25 50
31 89
...
Tab is pressed between each number in the first row and each number in the second.
I've come up with this so far (commented out section is to be used for determining the GCD):
/*
File name: euclid.cpp
This program find the largest common multiple of two numbers using the Euclid method.
*/
#include <stdio.h>
#include "genlib.h"
#include "simpio.h"
int main()
{
FILE *input;
long num1=0, num2=0, orinum2=0, rem=0, gcd=0;
int i=0, size=0;
char temp;
input=fopen("Euclid.txt", "r");
while((temp=getc(input))!=EOF)
{
if(temp=='\n') size++;
}
size++;
while(i<size)
{
fscanf(input, "%d\t%d%[^\n]", &num1, &num2);
printf("%d\t%d\n", num1, num2);
orinum2=num2;
/* while (true)
{
rem=num1%num2;
if (rem==0)
{
gcd=num2; break;
}
else
{
num1=num2;
num2=rem;
}
}
printf("The GCD of %d and %d is %d.\n", num1, orinum2, gcd);
*/ i++;
}
fclose(input);
}
Every single webpage and resource I have checked dictates that this should work, but for some reason it just isn't.

fscanf will "return the number of input items successfully matched and assigned":
#include <stdio.h>
int main()
{
FILE *input = fopen("input.txt", "r"); ;
int num1, num2;
while(fscanf(input, "%d %d", &num1, &num2) > 0)
printf("%d\t%d\n", num1, num2);
fclose(input);
}
The pattern ("%d %d") will match and assign two integers, separated by any number of whitespace characters.
Whitespace characters include your tab (\t), and newline (\n).

Related

How can we determine whether a socket is ready to read/write?

How can we determine whether a socket is ready to read/write in socket programming.
On Linux, use select() or poll().
On Windows, you can use WSAPoll() or select(), both from winsock2.
Mac OS X also has select() and poll().
#include <sys/select.h>
int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout);
select() and pselect() allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform the corresponding I/O operation (e.g., read(2)) without blocking. – https://linux.die.net/man/3/fd_set
#include <poll.h>
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
poll() performs a similar task to select(2): it waits for one of a set of file descriptors to become ready to perform I/O.
– https://linux.die.net/man/2/poll
Example of select usage:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int
main(void)
{
fd_set rfds;
struct timeval tv;
int retval;
/* Watch stdin (fd 0) to see when it has input. */
FD_ZERO(&rfds);
FD_SET(0, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(1, &rfds, NULL, NULL, &tv);
/* Don't rely on the value of tv now! */
if (retval == -1)
perror("select()");
else if (retval)
printf("Data is available now.\n");
/* FD_ISSET(0, &rfds) will be true. */
else
printf("No data within five seconds.\n");
exit(EXIT_SUCCESS);
}
Explanation of the above code:
FD_ZERO initializes the rfds set. FD_SET(0, &rfds) adds fd 0 (stdin) to the set. FD_ISSET can be used to check whether a specific file descriptor is ready after select returns.
The select call in this example waits until rfds has input or until 5 seconds passes. The two NULLs in the select call are where file descriptor sets (fd_sets) to be checked for ready to write status and exceptions, respectively, would be passed. The tv argument is the number of seconds and microseconds to wait. The first argument to select, nfds, is the highest numbered file descriptor in any of the three sets (read, write, exceptions sets) plus one.
Example of poll usage (from man7.org):
/* poll_input.c
Licensed under GNU General Public License v2 or later.
*/
#include <poll.h>
#include <fcntl.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \
} while (0)
int
main(int argc, char *argv[])
{
int nfds, num_open_fds;
struct pollfd *pfds;
if (argc < 2) {
fprintf(stderr, "Usage: %s file...\n", argv[0]);
exit(EXIT_FAILURE);
}
num_open_fds = nfds = argc - 1;
pfds = calloc(nfds, sizeof(struct pollfd));
if (pfds == NULL)
errExit("malloc");
/* Open each file on command line, and add it 'pfds' array. */
for (int j = 0; j < nfds; j++) {
pfds[j].fd = open(argv[j + 1], O_RDONLY);
if (pfds[j].fd == -1)
errExit("open");
printf("Opened \"%s\" on fd %d\n", argv[j + 1], pfds[j].fd);
pfds[j].events = POLLIN;
}
/* Keep calling poll() as long as at least one file descriptor is
open. */
while (num_open_fds > 0) {
int ready;
printf("About to poll()\n");
ready = poll(pfds, nfds, -1);
if (ready == -1)
errExit("poll");
printf("Ready: %d\n", ready);
/* Deal with array returned by poll(). */
for (int j = 0; j < nfds; j++) {
char buf[10];
if (pfds[j].revents != 0) {
printf(" fd=%d; events: %s%s%s\n", pfds[j].fd,
(pfds[j].revents & POLLIN) ? "POLLIN " : "",
(pfds[j].revents & POLLHUP) ? "POLLHUP " : "",
(pfds[j].revents & POLLERR) ? "POLLERR " : "");
if (pfds[j].revents & POLLIN) {
ssize_t s = read(pfds[j].fd, buf, sizeof(buf));
if (s == -1)
errExit("read");
printf(" read %zd bytes: %.*s\n",
s, (int) s, buf);
} else { /* POLLERR | POLLHUP */
printf(" closing fd %d\n", pfds[j].fd);
if (close(pfds[j].fd) == -1)
errExit("close");
num_open_fds--;
}
}
}
}
printf("All file descriptors closed; bye\n");
exit(EXIT_SUCCESS);
}
Explanation of above code:
This code is a bit more complex than the previous example.
argc is the number of arguments. argv is the array of arguments given to the program. argc[0] is usually the name of the program. If argc is less than 2 (which means only one argument was given), the program outputs a usage message and exits with a failure code.
pfds = calloc(nfds, sizeof(struct pollfd)); allocates memory for an array of struct pollfd which is nfds elements long and zeroes the memory. Then there is a NULL check; if pfds is NULL, that means calloc failed (usually because the program ran out of memory), so the program prints the error with perror and exits.
The for loop opens each filename specified in argv and assigns it to corresponding elements of the pfd array. Then sets .events on each element to POLLIN to tell poll to check each file descriptor for whether it is ready to read
The while loop is where the actual call to poll() happens. The array of struct pollfds, pfds, the number of fds, nfds, and a timeout of -1 is passed to poll. Then the return value is checked for error (-1 is what poll return when there is an error) and if there is an error, the program prints an error message and exits. Then the number of ready file descriptors is printed.
In the second for loop inside the while loop, the program iterates over the array of pollfds and checks the .revents field of each structure. If that field is nonzero, an event occurred on the corresponding file descriptor. The program prints the file descriptor, and the event, which can be POLLIN (ready for input), POLLHUP (hang up), or POLLERR (error condition). If the event was POLLIN, the file is ready to be read.
The program then reads 10 bytes into buf. If an error happens when reading, the program prints an error and exits. Otherwise, the program prints the number of bytes read and the contents of the buffer buf.
In case of error or hang up (POLLERR, POLLHUP) the program closes the file descriptor and decrements num_open_fds.
Finally the program says that all file descriptors are closed and exits with EXIT_SUCCESS.

STM32 GSM AT command response parser

I am sending AT command to get IMEI no.
char CGSN[] = "AT+CGSN\r\n";
// in while loop
HAL_UART_Transmit(&huart2,(uint8_t *)CGSN, sizeof(CGSN),100);
HAL_Delay(1000);
HAL_UART_Receive_IT(&huart2,(uint8_t *)&ch,1);
// Callback
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance == USART2){
if(buf[i]!=13){
buf[i]=ch;
i++;
}
}
HAL_UART_Receive_IT(&huart2,(uint8_t *)&ch,1);
buf[i]=0;
}
the response stored in buffer is - \r\n9876543212345\r\n\r\nOK\r\n
What is best way to receive response and filter out n"9876543212345" & "OK" and store separately in a array to further process
Thanks
You can use sscanf for this purpose. Below is the quick implementation of the scenario in C.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(void) {
unsigned long a;
char array[10];
char string[] = "\r\n9876543212345\r\n\r\nOK\r\n";
sscanf(string , "\r\n%ld\r\n\r\n%s\r\n", &a, array);
printf("%ld %s\n", a, array);
return 0;
}
Problem is simple! Your buf[] dont include '\r' (in decimal 13).
Correct value buf[] is "AT+CGSN\n9876543212345\n\nOK\n\0".

Behavior of select() on stdin when used on a pipe

I am trying to understand an observation on behavior of select() when used on stdin, when it is receiving data from a pipe.
Basically I had a simple C program using the following code:
hello.c:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <termios.h>
int main(int argc, char *argv[])
{
int flags, opt;
int nsecs, tfnd;
fd_set rfds;
struct timeval tv;
int retval;
int stdin_fileno_p1 = STDIN_FILENO+1;
char c;
int n;
/* Turn off canonical processing on stdin*/
static struct termios oldt, newt;
tcgetattr( STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON);
tcsetattr( STDIN_FILENO, TCSANOW, &newt);
while (1)
{
FD_ZERO(&rfds);
FD_SET(STDIN_FILENO, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 0;
retval = select(stdin_fileno_p1, &rfds, NULL, NULL, &tv);
if ( retval && (retval!=-1) )
{
n = read(STDIN_FILENO, &c, 1);
write(STDOUT_FILENO, &c, 1);
}
else printf("No Data\n");
usleep(100000);
}
tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
}
If I ran the program as follows I could see characters echoing when I type keys on while the program is running. When keys are not pressed, it displays "No Data" as expected.
./hello
However, if use the program as follows, the program never gets to a state where is displays "No Data". Instead last character "c" is repeatedly displayed.
echo -n abc | ./hello
I'm a bit puzzled by this observation, and would be grateful if you could help me to understand the observed behavior.
The problem is that your program does not detect an end-of-file condition when it reads from the STDIN_FILENO descriptor. After echo has written the c character it will close its end of the pipe, which will cause the select in your program to return immediately and your read to return 0 as an indication that no more data will ever be available from that descriptor. Your program doesn't detect that condition. Instead it just calls write with whatever character was left in the buffer by the last successful read and then repeats the loop.
To fix, do if (n==0) break; after the read.

Losing values with iterative realloc in C

I am working in C with Netbeans8.0
I have to read files in an iterative approach to get list of words. That is, in single iteration a file is read into an array of strings and then merge this array into a single array.
void merge_array(char** a,int* M, char** b,int N)
{
//............. Add extra memory to a ..............*/
void *tmp = realloc(a, (*M+N) * sizeof(*a));
if (tmp == NULL)
{
perror("Merging -> Could not reallocate");
exit(EXIT_FAILURE);
}
a = tmp;
memset(a+(*M), 0, N*sizeof(*a));
//............. copy strings in b to a ..............*/
int i,j=0;
for(i=*M; i<((*M)+N); i++)
{
size_t wlen = strlen(b[j]);
a[i] = malloc((wlen+1) * sizeof(char));
if (a[i] == NULL)
{
perror("Failed to replicate string");
exit(EXIT_FAILURE);
}
memcpy(a[i], b[j], wlen+1);
j++;
}
(*M) = (*M)+N; // resetting the count
printf("Confirm - %s, %d\n",a[0],*M);
}
Above function reads the contents of a file. In main above function is called iteratively and merged into a single array named 'termlist'. Main code is given below
char** termlist;
int termCount=0;
while(files[i]){
char **word_array;
int wdCnt,a;
char* tmp = (char*) malloc(strlen(path)*sizeof(char));
strcpy(tmp,path); strcat(tmp,files[i]); strcpy(files[i],tmp);
printf("\n\n******* Reading file %s...\n",files[i]);
word_array = getTerms_fscanf(files[i],&a); //reading contents of file
wdCnt = a;
if(i==0) // before reading the first file initializing the termlist
{
termlist = (char**) malloc(wdCnt*sizeof(char*));
}
merge_array(termlist,&termCount,word_array,wdCnt);
printf("CHECK - %s, %d\n",termlist[0],termCount);
free(word_array);
++i;
}
Now the problem is that,
After 1st two iterations, Inside function everything works fine but in main values of termlist[0], termlist[1] turns out to be junk.. That is first 2 words read from first file is lost. The 3rd iteration returns with failure at merge_array function call.
Output is
******* Reading F:/Netbeans C/Test Docs/doc1.txt...
Confirm - tour, 52
CHECK - tour, 52
******* Reading F:/Netbeans C/Test Docs/doc2.txt...
Confirm - tour, 71
CHECK - Ôk'aÔk'a`œ€`œ€äk'aäk'aìk'aìk'aôk'aôk'aük'aük'ah“€, 71
I am not able to identify problem with this.. Please help with this..

why my PCRE only matches the first result

I want to match all 'abc' in the input string. But I got the following result when input "first abc, second abc, third abc". I also output the ovector:
src: first abc, second abc, third abc
Matches 1
ovector: 6|9|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|
My code:
#include <stdio.h>
#include <string.h>
#include "pcre.h"
static const char my_pattern[] = "abc";
static pcre* my_pcre = NULL;
static pcre_extra* my_pcre_extra = NULL;
void my_match(const char* src)
{
printf("src: %s\n", src);
int ovector[30]={0};
int ret = pcre_exec(my_pcre, NULL, src, strlen(src), 0, 0, ovector, 30);
if (ret == PCRE_ERROR_NOMATCH){
printf("None match.\n");
}
else{
printf("Matches %d\n",ret);
}
printf("ovector: ");
for(int i=0;i<sizeof(ovector)/sizeof(int);i++){
printf("%d|",ovector[i]);
}
printf("\n");
return;
}
int main()
{
const char* err;
int erroffset;
my_pcre = pcre_compile(my_pattern, PCRE_CASELESS, &err, &erroffset, NULL);
my_pcre_extra = pcre_study(my_pcre, 0, &err);
my_match("first abc, second abc, third abc");
return 0;
}
How can I get all the 'abc's, thanks.
pcre_exec only finds one match at a time. ovector is for substring matches. int ovector[30]={0}; will give you up to 10 matches (the last third (20-29) is not used), the first pair of numbers is for the whole pattern, the next pair is for the first capturing parentheses and so on. E.g. if you change your pattern to:
`static const char my_pattern[] = "(a(b)c)";`
then in your output you should see
Matches 3
ovector: 6|9|6|9|7|8|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|
The function returns the number of captures that matched, in this case three, one for the whole pattern and two subpattern captures. The whole pattern matches at 6-9, the first parentheses match 6-9 too and the second parentheses match 7-8. To get more whole matches (global) you have to use a loop, passing in the offset of the previous match (ovector[1]) each time.
See http://www.pcre.org/pcre.txt and search for How pcre_exec() returns captured substrings