I need to make a program which takes as input on text file and output the same string with one replaced word; the main function will take 3 parameters (wordR, wordS, file). So can anyone help me with a good tip how I can scan the words in c?
Go with strtok() or strtok_r() function.
The obvious possibility would be [fs]scanf's "%s" conversion:
char one_word[64];
fscanf(input_file, "%63s", one_word);
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 Buffer received as a result of recvfrom(). lets say,
char buffer[12] = "Hello 1";
I want to separate Hello and 1 and store them in different buffers so that one buffer has "Hello" in it and other buffer or an int variable has "1" stored in it.
In other words I want to separate contents of a buffer on the basis of spaces. How can this be done?
I tried:
int number;
char buff[7];
sscanf (buffer,"%s %d",buff,number);
Will this approach work?
If there are only 2 words your idea will work. But there is a small error in your code.
Change the sscanf this way
sscanf (buffer,"%s %d",buff,&number);
This approach works but you need to change to change your sscanf to:
sscanf (buffer,"%s %d",buff,&number);
The %d expects an int* and you are sending an int.
Looks like you want strtok, it can do exactly that. But make sure your string is NULL-terminated, recv and other socket functions don't do that for you and the standard C string functions do expect NULL-termination.
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
writing another program, it reads a txt file, and stores all the letter characters and spaces (as \0) in a char array, and ignores everything else. this part works.
now what i need it to do is read a user inputted string, and search for that string in the array, then print the word every time it appears. im terrible at I/O in C, how do you read a string then find it in a char array?
#include <stdio.h>
...
char str [80];
printf ("Enter your word: ");
scanf ("%s",str);
char* pch=strstr(fileData,str);
while (pch!=NULL)
{
printf ("found at %d\n",pch-fileData+1);
pch=strstr(pch+1,str);
}
read in the user inputted string as a char array as well (cause strings are basically char* anyway in C)
use a string matching algorithm like Boyer-Moore or Knutt-Morris-Pratt (more popularly known as KMP) - google for it if you like for C implementations of these - cause they're neat, tried and tested ways of searching strings for substrings and pattern matches and all.
for each of these indexOf cases, print the position where the word is found maybe? or if you prefer, the number of occurrences.
Generally, the list of C string functions, found here, say, are of the format str* or strn*, depending on requirements.
One for-loop inside another for-loop (called nested loop). Go through all the letters in your array, and for each letter go through all the letters in your input string and find out if that part of the array matches with the input string. If it does, print it.
I'm writing a program for a school project that is supposed to emulate the Unix shell, in a very basic form. It's basically parsing input, then doing a fork/exec. I need to be able to read arguments in the program (not as arguments passed to the program from the command line) individually. For example, I will prompt:
Please enter a command:
...and I need to be able to parse both...
ls
OR
ls -l
but the trouble is that there seems to be no easy way to do this. scanf() will pull each argument individually, but I see no way to place them into differing slots in a char* array. For example, if I do...
char * user_input[10];
for (int i=0; i<10; i++){
user_input[i] = (char *) malloc(100*sizeof(char));
}
for (int i=0; *(user_input[i]) != '#'; i++)
{
scanf("%s", user_input[index]);
index++;
}
...then user_input[0] will get "ls", then the loop will start over, then user_input[0] will get "-l".
gets and fgets just take the whole line. Obviously this problem can be logically solved by going through and plucking out each individual argument...but I'd like to avoid having to do that if there is an easy way that I'm missing. Is there?
Thanks!
If your use case is simple enough, you can do this with strtok:
char *strtok(char *str, const char *delim);
char *strtok_r(char *str, const char *delim, char **saveptr);
The strtok() function parses a string into a sequence of tokens. On the first call to strtok() the string to be parsed should be specified in str. In each subsequent call that should parse the same string, str should be NULL.
You can use strtok or strtok_r to split the string on spaces.
If you're doing something more complex, where some of the arguments could have (quoted) spaces in them, you're pretty much stuck parsing it yourself - though you could have a look at the source of a shell (e.g. bash) to see how it handles it.
kilanash helpfully reminds me of my obvious omission - GNU getopt. You'll still have to have parsed into separate arguments yourself first, though.
Forget that scanf exists for it rarely does what you want. Get the whole line at once and then write code to split it up. strtok - the second most favored answer to this question - is also problem ridden.
You can use strtok_r to break the string up on whitespace. Note that it is a destructive operation (modifies the input string).
Try to see if anything of this will help you:
ANSI C Command Line Option Parsing Library
The Argtable Homepage
Regards,
Tiho