Split csv file name to get data using C language - c

I have c variable file_path -
"a/b/c/xx.xxx_LOB_xxxx.caseno_YYYYMMDD.seq_no.csv"
From this file_path variable, I want to get the value of file_name excluding path,LOB,caseno,file_date(YYYYMMDD) and seq_no using C language in different variables. I tried with strtok() but not able to get the values.
Can you suggest how will get the value of each variable?
Thank you.

You have several options to separate the string. (you always have several options for parsing strings in C) You can always use a pair of pointers to work your way down the input string, bracketing and copying any set of characters between the two pointers. (you can operate on a non-mutable string like a String Literal because the original isn't modified)
You can use strtok() to help break the original up into smaller parts (sometimes into exactly what you need). However in this case, since '_' can be both a delimiter as well as be an included character in what you extract, you would still need to manually parse what you need from the tokens separated by strtok(). (strtok() modifies the string it operates on, so it must be mutable)
A third option is to craft a format-string and use sscanf() to parse the variables from the input. Since your format is fixed -- you are in luck and you can simply use sscanf to separate what you need. If you are not intimately familiar with the sscanf format-string and all of the modifiers and conversion specifiers, then spend an hour reading, and understanding, man 3 scanf -- time spent will save you ten-fold hours later.
Your fixed format, assuming no one variable in the string can be greater that 127-characters (adjust as necessary), can be accommodated with the format string:
" %*[^_]_%127[^_]%*[^.].%127[^_]_%127[^.].%127[^.]"
The string is separated into 4 strings. The parts of the string that are not needed are discarded using the assignment suppression operator the '*'. If you are separating the input into an array of strings arr, then you can write a simple function to handle the separation for you, e.g.
int varsfrompath (char (*arr)[MAXLEN], char *str)
{
int i = sscanf (str, " %*[^_]_%127[^_]%*[^.].%127[^_]_%127[^.].%127[^.]",
arr[0], arr[1], arr[2], arr[3]);
return i == EOF ? 0 : i; /* return no. of vars separated */
}
Which returns the number of items successfully parsed from the string. (zero if an input failure occurs)
A working example would be:
#include <stdio.h>
#include <string.h>
#define NELEM 4
#define MAXLEN 128
int varsfrompath (char (*arr)[MAXLEN], char *str)
{
int i = sscanf (str, " %*[^_]_%127[^_]%*[^.].%127[^_]_%127[^.].%127[^.]",
arr[0], arr[1], arr[2], arr[3]);
return i == EOF ? 0 : i; /* return no. of vars separated */
}
int main (void) {
char fname[] = "a/b/c/xx.xxx_LOB_xxxx.caseno_YYYYMMDD.seq_no.csv",
results[NELEM][MAXLEN] = { "" };
int n = varsfrompath (results, fname);
for (int i = 0; i < n; i++)
printf ("results[%2d] = '%s'\n", i, results[i]);
}
Example Use/Output
$ ./bin/varsfrompath
results[ 0] = 'LOB'
results[ 1] = 'caseno'
results[ 2] = 'YYYYMMDD'
results[ 3] = 'seq_no'
This is by far the simplest way to handle your fixed format. A manual parse with a pair of pointers is more involved from an accounting (for where you are in the string standpoint), but no more difficult. (tedious may be the word)
Look things over and if I misinterpreted your separation needs, let me know and I can adjust it.
Manual Parse Using a Pair of Pointers
If rather than spend time with the man 3 scanf man page, you would rather spend time with an 8.5x11 sheet of paper and pencil with your accounting hat on to do the same thing using a pair of pointers, then you could do something similar to the following.
You have a start pointer sp and end pointer ep and you simply work down your line of input to anchor the sp before the variable to extract, and the ep at the end of the variable and then use memcpy() to copy the characters between them. (you will have to adjust by 1 on occasion depending on whether you are pointing at the beginning of the variable you want, or once character before it to the delimiter. (the easy way to get your arithmetic right when working down the string is to only consider there being 1-char between the start and end pointers -- that way whether you need to add or subtract 1 to work around your delimiters will be clear)
You can replace the varsfrompath function above with the one that follows and receive the same results, e.g.:
int varsfrompath (char (*arr)[MAXLEN], const char *str)
{
char *sp, *ep; /* start pointer, end pointer */
int i = 0;
/* set sp to 1st '_' and ep to second '_', copy to arr and nul-terminate */
if (!(sp = strchr (str, '_')) || /* can't find 1st '_' */
!(ep = strchr (sp + 1, '_')) || /* can't find 2nd '_' */
ep - sp - 2 > MAXLEN) /* chars between -1 > MAXLEN */
return 0;
memcpy (arr[i], sp + 1, ep - sp - 1); /* copy ep - sp - 1 chars */
arr[i++][ep - sp - 1] = 0; /* nul-terminate */
sp = ++ep; /* set sp to 1-past ep */
/* set sp to next '.' and ep to next '_", copy to arr and nul-terminate */
if (!(sp = strchr (sp, '.')) || /* can't find next '.' */
!(ep = strchr (sp + 1, '_')) || /* can't find next '_' */
ep - sp - 2 > MAXLEN) /* chars between -1 > MAXLEN */
return i;
memcpy (arr[i], sp + 1, ep - sp - 1); /* copy ep - sp - 1 chars */
arr[i++][ep - sp - 1] = 0; /* nul-terminate */
sp = ++ep; /* set sp to 1-past ep */
/* set ep to next '.', copy to arr and nul-terminate */
if (!(ep = strchr (sp, '.')) || ep - sp - 2 > MAXLEN) /* no '.' or too long */
return i;
memcpy (arr[i], sp, ep - sp); /* copy ep - sp chars */
arr[i++][ep - sp] = 0; /* nul-terminate */
sp = ++ep; /* set sp to 1-past ep */
/* repeate exact same steps for last var */
if (!(ep = strchr (sp, '.')) || ep - sp - 2 > MAXLEN)
return i;
memcpy (arr[i], sp, ep - sp);
arr[i++][ep - sp] = 0;
sp = ++ep;
return i; /* return no. of vars separated */
}
It may look more complicated, but you are actually just using simple string functions like strchr() to position the pointers, and then just extracting the characters between them. Compare and contrast both approaches.

Related

split a user inputed string at a specific letter in c

I am trying to write an if else statement that looks at a user input and then splits it after index[1] if the string includes the letter b or split after index[0] if the string input doesnt include the letter b. How would I approach that? Pretty new to C so not too sure.
This is what I have so far... I think im on the right path and am trying to figure out how I would finish it off so it does what I want it to do.
int split_note_and_chord(char* string, char* note, char* chord)
{
for(user input doesnt have b in it)
{
if(i = 0; i <index; i++)
{
note[i] = string[i];
}
note[index] = 0;
else{ if(i = 0; i < index; i++)
{
note[i] = strlen(string[2]);
}
}
}
C string is nothing but a char array
string.h provides handy functions to check the string contents
you can use if condition and strstr and strchr functions for your logic
For example
#include <stdio.h>
#include <string.h>
int main () {
const char *input = "backwards";
char *ret;
ret = strstr(input, "b");
if( ret != NULL ) {
} else {
}
}
The strstr will return NULL if the b does not exist
You can also use strchr if you want the second argument as single char strchr(input, 'b');
There are a number of ways to approach splitting your input string after the 2nd character if the input contains 'b' or after the 1st character otherwise. Since you are dealing with either a 1 or 2, all you need to do is determine if 'b' is present. The easiest way to do that is with strchr() which will search a given string for the first occurrence of a character, returning a pointer to that character if found, or NULL otherwise. See man 3 strchr
So you can use strchr to test if 'b' is present, if the return isn't NULL split the string after the 2nd character, if it is NULL, split it after the first.
A simple implementation using a ternary to set the split-after size for input read into a buffer buf would be:
char part2[MAXC]; /* buffer to hold 2nd part */
size_t split; /* number of chars to split */
/* if buf contains 'b', set split at 2, otherwise set at 1 */
split = strchr(buf, 'b') ? 2 : 1;
strcpy (part2, buf + split); /* copy part2 from buf */
buf[split] = 0; /* nul-terminate buf at split */
A quick implementation allowing you to enter as many strings as you like and it will split after the 1st or 2nd character depending on the absense, or presence of 'b' would be:
#include <stdio.h>
#include <string.h>
#define MAXC 1024 /* if you need a constant, #define one (or more) */
int main (void) {
char buf[MAXC]; /* buffer to hold line of input */
fputs ("Enter a string to split (or [Enter] alone to exit)\n\n"
"string: ", stdout);
while (fgets (buf, MAXC, stdin)) { /* loop reading each line */
char part2[MAXC]; /* buffer to hold 2nd part */
size_t split; /* number of chars to split */
if (*buf == '\n') /* if [Enter] alone, exit */
break;
/* if buf contains 'b', set split at 2, otherwise set at 1 */
split = strchr(buf, 'b') ? 2 : 1;
strcpy (part2, buf + split); /* copy part2 from buf */
buf[split] = 0; /* nul-terminate buf at split */
printf (" part1: %s\n part2: %s\nstring: ", buf, part2);
}
}
(note: if you are unfamiliar with the ternary operator, it is simple (test) ? if_true : if_false. Above it is just shorthand for if (strchar (buf, 'b') != NULL) split = 2; else split = 1;)
Example Use/Output
$ ./bin/splitb
Enter a string to split (or [Enter] alone to exit)
string: look out
part1: l
part2: ook out
string: look out below
part1: lo
part2: ok out below
string:
Let me know if this is what you intended. If not, I'm happy to help further. Also, if you have any questions, just let me know.
Edit Based on Comment
It is still unclear what your list of notes are in your header file, but you can simply use a string constant to contain the letters of the notes, e.g.
#define NOTES "abcdefg" /* (that can be a string constant as well) */
(you can add upper case if needed or you can convert the input to lower -- whatever works for you)
If you simply need to find the first occurrence of one of the letters in the NOTES string, then strpbrk() will allow you to do just that returning a pointer to the first character of NOTES found in your string. (you must have some way to handle the user entering, e.g. "the note cflat", which would split on the first 'e' instead of 'c', but you will need to provide further specifics there)
Another consideration is how long note can be. If it is always 1-character, then you can simplify by just comparing against the first character in the string using strchr (NOTES, buf[0]) (which turns the way you normally think about using strchr() around -- using the fist string NOTES and the first char read from user input.
Taking a general approach that would break "---cflat---" into "---c" and "flat---", your function could be similar to:
int split_note_and_chord (char *string, char *note, char *chord)
{
char *p = strpbrk (string, NOTES); /* pointer to first of NOTES in string */
if (p != NULL) { /* if found */
strcpy (note, string); /* copy string to note */
note[p - string + 1] = 0; /* nul-terminate after note */
strcpy (chord, p + 1); /* copy rest to chord */
return 1; /* return success */
}
*note = 0; /* make note and chord empty-string */
*chord = 0;
return 0; /* return failure */
}
(note: if there is no char in NOTES found, then note and chord are made the empty-string by nul-terminating at the first character before returning zero to indication no-note found.)
A quick implementation similar to the first could be:
#include <stdio.h>
#include <string.h>
#define MAXC 1024 /* if you need a constant, #define one (or more) */
#define NOTES "abcdefg" /* (that can be a string constant as well) */
int split_note_and_chord (char *string, char *note, char *chord)
{
...
}
int main (void) {
char buf[MAXC], /* buffer to hold line of input */
note[MAXC], /* buffer for node */
chord[MAXC]; /* buffer for chord */
fputs ("Enter a string with node and chord (or [Enter] alone to exit)\n\n"
"string: ", stdout);
/* loop reading each line until [Enter] alone */
while (fgets (buf, MAXC, stdin) && *buf != '\n') {
if (split_note_and_chord (buf, note, chord))
printf (" note : %s\n chord : %s\n", note, chord);
else
fputs ("\nerror: note not found in string.\n\n", stderr);
fputs ("string: ", stdout);
}
return 0;
}
(note: that using fgets() will read and include the '\n' resulting from the user pressing Enter in buf and thus it will also be included in the remainder copied to chord. You can use buf[strcspn (buf, "\n")] = 0; to trim it from buf -- or from chord by substituting chord for buf in the call using strcspn() as the index to nul-terminate at.)
(also note: you can adjust MAXC to fit your needs -- which is why you declare a constant in the first place -- to make it a simple change of one line at the top of your file)
Example Use/Output
Using your function to split various input would result in the following:
$ ./bin/splitb3
Enter a string with node and chord (or [Enter] alone to exit)
string: ---cflat---
note : ---c
chord : flat---
string: asharp
note : a
chord : sharp
string: bflat
note : b
chord : flat
string: hook
error: note not found in string.
string: c
note : c
chord :
There are many, many different way to do this and how to best approach it will depend on how you have your notes and chords defined in your header -- as well as what, if any, limitations you put on what format you require the user to enter. If you need more help, please edit your question and Add the contents of your header so we will know how they are declared and defined, as well as listing any constraints you want to place on what the user can enter.

Replacing a whole word and not substrings in a string in C

I am trying to replace a whole word in C array of characters and skip the substrings. I made research and I ended up with really hard resolutions while I think I have better idea if someone can give me a hand.
Let's say I have the string:
char sentence[100]= "apple tree house";
And I would like to replace tree with the number 12:
"apple 12 house"
I know that the words are delimited by space so my idea is to :
1.Tokenize the string with delimiter white space
2.In the while loop checking with the library function STRCMP if the string is equal to the token and if it is then to be replaced.
The problem for me comes when I try to replace the string as I couldn't make it.
void wordreplace(char string[], char search[], char replace[]) {
// Tokenize
char * token = strtok(string, " ");
while (token != NULL) {
if (strcmp(search, token) == 0) {
REPLACE SEARCH STRING WITH REPLACE STRING
}
token = strtok(NULL, " ");
}
printf("Sentence : %s", string);
}
Any suggestions what I can use ? I guess it might be really simple but I am beginner much appreciated :)
[EDIT]: Spaces are the only delimiters and usually the string to be replaced is not longer than the original.
I would avoid strtok in this case (because it will modify the string as a side effect of tokenizing it), and approach this by looking at the string essentially character-by-character and maintaining a "read" and "write" index. Because the output can never be longer than the input, the write index will never get ahead of the read one, and you can "write-back" and make the change within the same string.
To visualize this, I find it useful to write out the input in boxes and draw arrows to current read and write indexes and track through the process so you can verify that you have a system that will do what you want it to do and that your loops and indexes all work like you expect.
Here is one implementation that matches how my own mind tends to approach this sort of algorithm. It walks the string and looks ahead to try matching from the current character. If it finds a match, it copies the replace onto the current spot, and increments both indexes accordingly.
void wordreplace(char * string, const char * search, const char * replace) {
// This is required to be true since we're going to do the replace
// in-place:
assert(strlen(replace) <= strlen(search));
// Get ourselves set up
int r = 0, w = 0;
int str_len = strlen(string);
int search_len = strlen(search);
int replace_len = strlen(replace);
// Walk through the input character by character.
while (r < str_len) {
// Is this character the start of a matching token? It is
// if we see the search string followed by a space or end of
// string.
if (strncmp(&string[r], search, search_len) == 0 &&
(string[r+search_len] == ' ' || string[r+search_len] == '\0')) {
// We matched the search token. Copy the replace token.
memcpy(&string[w], replace, replace_len);
// Update our indexes.
w += replace_len;
r += search_len;
} else {
// Otherwise just copy this character.
string[w++] = string[r++];
}
}
// Be sure to terminate the final version of the string.
string[w] = '\0';
}
(Note that I tweaked your function signature to use the more idiomatic pointer notation rather than char arrays, and per flu's comment below, I marked the search and replace tokens as "const" which is a way of the function advertising that it will not modify those strings.)
To do what you want to do becomes a little more involved because you need to handle the scenarios where:
replacement is shorter than original -- so you will need to move the remainder of line to follow the replacement text to avoid leaving empty space;
replacement is same length as original -- trivial case, just overwrite original with replacement; and finally
replacement is longer than original -- where you must validate the original string plus the replacement length difference will still fit in the storage for the original string, you must copy the end of line to a temporary buffer before making the replacement, and then add the rest of the line in the temporary buffer to the end.
strtok is some disadvantages here due to it making changes to the original string during the tokenizing process. (you can just make a copy, but if you want an in-place replacement, you need to look further). A combination of strstr and strcspn allow you to operate on the original string in more efficient manner when looking for a specific search string within the original.
strcspn can be used like strtok with the set of delimiters to provide the length of the current token found (to ensure strstr didn't match your search term as a lesser-included-substring of a longer word, like tree in trees) Then it becomes a simple matter of looping with strstr and validating the length of the token with strcspn and then just applying one of the three cases above.
A short example implementation with comments included in-line to help you follow along could be:
#include <stdio.h>
#include <string.h>
#define MAXLIN 100
void wordreplace (char *str, const char *srch,
const char *repl, const char *delim)
{
char *p = str; /* pointer to str */
size_t lenword, /* length of word found */
lenstr = strlen (str), /* length of total string */
lensrch = strlen (srch), /* length of search word */
lenrepl = strlen (repl); /* length of replace word */
while ((p = strstr (p, srch))) { /* srch exist in rest of string? */
lenword = strcspn (p, delim); /* get length of word found */
if (lenword == lensrch) { /* word len match search len */
if (lenrepl == lensrch) /* if replace is same len */
memcpy (p, repl, lenrepl); /* just copy over */
else if (lenrepl > lensrch) { /* if replace is longer */
/* check that additional lenght will fit in str */
if (lenstr + lenrepl - lensrch > MAXLIN - 1) {
fputs ("error: replaced length would exeed size.\n",
stderr);
return;
}
if (!p[lenword]) { /* if no following char */
memcpy (p, repl, lenrepl); /* just copy replace */
p[lenrepl] = 0; /* and nul-terminate */
}
else { /* store rest of line in buffer, replace, add end */
char endbuf[MAXLIN]; /* temp buffer for end */
size_t lenend = strlen (p + lensrch); /* end length */
memcpy (endbuf, p + lensrch, lenend + 1); /* copy end */
memcpy (p, repl, lenrepl); /* make replacement */
memcpy (p + lenrepl, endbuf, lenend); /* add end after */
}
}
else { /* otherwise replace is shorter than search */
size_t lenend = strlen (p + lenword); /* get end length */
memcpy (p, repl, lenrepl); /* copy replace */
/* move end to after replace */
memmove (p + lenrepl, p + lenword, lenend + 1);
}
}
}
}
int main (int argc, char **argv) {
char str[MAXLIN] = "apple tree house in the elm tree";
const char *search = argc > 1 ? argv[1] : "tree",
*replace = argc > 2 ? argv[2] : "12",
*delim = " \t\n";
wordreplace (str, search, replace, delim);
printf ("str: %s\n", str);
}
Example Use/Output
Your replace "tree" with "12" example in "apple tree house in the elm tree":
$ ./bin/wordrepl_strstr_strcspn
str: apple 12 house in the elm 12
A simple same-length replacement of "tree" with "core", e.g.
$ ./bin/wordrepl_strstr_strcspn tree core
str: apple core house in the elm core
The "longer than" replacemnt of "tree" with "bobbing":
$ ./bin/wordrepl_strstr_strcspn tree bobbing
str: apple bobbing house in the elm bobbing
There are many different ways you can approach this problem, so no one way is the right way. The key is to make it understandable and reasonably efficient. Look things over and let me know if you have further questions.

output formatted text using width and margin

I am trying to write a program that will take the following input and will format it and output it to a text file.
Here is a picture of how it should work
?mrgn left: Each line following the command will be indented left spaces from
the left-­­hand margin. Note that this indentation must be included in the page
width. If this command does not appear in the input file, then the value of left
is 0 (zero).
I did the following so far:
while (fgets(line, MAX_LINE_LEN-1, infile) != NULL){/*Read the first line if it is not empty*/
char last[MAX_WORD_LEN] = {0};
char *p;
for (p = strtok(line, " "); p; p = strtok(NULL, " ")){
if(*last && strcmp(last, width)==0){
iwidth = atoi(p);
printf("width = %d\n", iwidth);
}
if(*last && strcmp(last, margin)==0){
imargin = atoi(p);
printf("margin = %d\n", imargin);
}
strncpy (last, p, MAX_WORD_LEN);
if(iwidth != 0 || imargin != 0){
printf("%s ", p);
}else{
printf("%s", line);
}
}
}
I am able to store the value of width and margin to a variable. I am now stuck on how I can specify the required formatting. I did some research but I couldn't find what I want. Please help!
Thank you!
Cheers!
After you have had several hours to work on the problem, let me give you a few pointers (no pun intended) that may help simplify your approach to the problem. While you can certainly use strtok to parse your option and width from the input file, there really is no need to tokenize when you know the line format containing the option will be "?name value".
A simplified approach, knowing your file contains the option as the first line, would simply be to read the entire line (using fgets or POSIX getline), verify the first character is '?' and then parse the option name and value from the line with sscanf. (you can either include the '?' in your format-string, or simply begin the parse at the 2nd character. (my choice) To accomplish this you could start with something similar to:
#include <stdio.h>
#include <string.h> /* for strcmp, strlen */
#define OPT 32 /* if you need constants, #define one (or more) */
#define WDTH 78
#define MAXC 1024
void str_word_wrap (char *buf, int n); /* wrap function prototype */
int main (void) {
char buf[MAXC] = "", /* buffer to hold words in file */
*p = buf, /* pointer to buf */
opt[OPT] = ""; /* buffer to hold option found in file */
int width = WDTH, /* variable holding width from option */
used = 0, /* number of chars used in buf */
val = 0; /* temp value to read option value from file */
/* option on line 1, read entire line */
if (!fgets (buf, MAXC, stdin) || *buf != '?')
fputs ("error: unexpected file format, using default width.\n\n",
stderr);
/* parse option and value, compare option is "width", use val as width */
if (sscanf (buf + 1, "%s %d", opt, &val) == 2) {
if (strcmp (opt, "width") == 0)
width = val;
}
...
At this point in your code, buf contains the first line, opt contains the option name, and width contains the width specified in the file (or the default width WDTH (78) in the event the first line did not contain the "?width val" information). Ideally, if the first line was not a valid option/value line, you would simply eliminate the excess whitespace from buf, add an ending ' ' and continue, but that code is left to you.
(note: I just redirect the file to stdin so I read from stdin instead of a file here -- but your infile is fine as well. You would just substitute infile where I read stdin)
Since you simply want to eliminate all the additional whitespace from your input file leaving a normally formatted paragraph which you will wrap to the specified width, using fscanf with the "%s" format specifier can handle the whitespace removal automatically. (with the scanf family, "%s" and numeric format specifiers ignore leading whitespace, "%c" and "%[..]" do not). So reading the remainder of the file into your buffer is simply a matter of reading each word in the file, keeping track of how many characters in your buffer you have used (so you know the next word will fit), and adding a ' ' (space) between each word as you add them to your buffer.
You can use strcat if that helps, or you can simply use a pointer and write a ' ' at one past the end of the current buffer and then a nul-terminating character past that on each iteration. Either way, just keep track of how many characters you have used so far and the len (length) of what you are adding, and then update your used count with the length of each word as you go. You could do something like the following:
while (scanf ("%s", p + used) == 1) { /* read each word, ignore WS */
size_t len = strlen (p + used); /* get length of word */
if (used + len + 2 >= MAXC) { /* make sure it fits with ' ' */
fputs ("warning: file truncated.\n", stderr);
break; /* note you can refine to save 1-char space at end */
}
*(p + used + len++) = ' '; /* add space at end of word */
*(p + used + len) = 0; /* nul-termiante after space */
used += len; /* update used with len */
}
*(p + --used) = 0; /* overwrite final ' ' with nul-character */
At this point you could write out your width value and the contents of your filled buffer for a check before you wrap the lines to width. I simply write the width used out before outputting the wrapped lines which completes the main() function of the program, e.g.
printf ("Wrapping file at width: %d\n\n", width);
str_word_wrap (buf, width); /* wrap buffer at width chars/output */
return 0;
}
All that remains is finishing the function to wrap the buffer to no more that width characters per line as you output your buffer. I provided the prototype above for str_word_wrap function and details in my original comment concerning the approach to wrapping the buffer by simply using a sliding-window of width length to work down your buffer, outputting the words that fit within the sliding window each time it is moved down the buffer.
To accomplish the task you generally use three pointers (I name then p the pointer to the current char, sp the start pointer for the window, and ep the end pointer for the window. The scheme is this, you begin with all three initialized to the beginning of your buffer, you then iterate over each char with p until p points to a space between the words, setting the end-pointer ep = p; each time a space is encountered. On each iteration you check if p - sp >= width, where p - sp is simply the current pointer address minus the start pointer address which tells you how many characters you have moved from the start. If that equals or exceeds your width, you know you last set ep (your end-pointer) to the last whitespace in the windows marking the end of the last word to output.
All that remains is outputting the line up to the end-pointer, (and a '\n') and then setting your new start-pointer to the next character after end-pointer and you can set your end-pointer to one after the current pointer (which slides your window forward) and you repeat. Nothing fancy is needed. Something like the following works fine:
void str_word_wrap (char *buf, int n)
{
char *p = buf, /* pointer to current char */
*sp = buf, /* pointer to start of line to print */
*ep = buf; /* pointer to end of line to print */
for (; *p && *p != '\n'; p++) { /* loop over each char (omit '\n')*/
if (*p == ' ') /* if space, set ep */
ep = p;
if (p - sp >= n) { /* if wrap length 'n' reached */
while (sp < ep) /* loop outputting chars sp -> ep */
putchar (*sp++);
putchar ('\n'); /* tidy up with '\n' */
sp = ++ep; /* set start to next after end */
ep = ++p; /* set end to next after current */
}
}
while (*sp && *sp != '\n') /* output last line of chars */
putchar (*sp++);
putchar ('\n'); /* tidy up with final '\n' */
}
Putting that altogether will handle your case, exactly:
Example Input File
$ cat dat/taggedparagraph.txt
?width 30
While there are enough characters here to
fill
at least one line, there is
plenty
of
white space that needs to be
eliminated
from the original
text file.
Now simply running the program using the file as input or redirecting the file to the programs stdin gives:
Example Use/Output
$ ./bin/wrapped_tagged_p < dat/taggedparagraph.txt
Wrapping file at width: 30
While there are enough
characters here to fill at
least one line, there is
plenty of white space that
needs to be eliminated from
the original text file.
Look things over and let me know if you have questions. This all boils down to basic pointer arithmetic and keeping track of where you are within a buffer while iterating over each character in the buffer to extract whatever specific information you need from it. You will often hear that referred to as "walking-a-pointer" over or down the buffer. Using a sliding-window is nothing more than walking-a-pointer while keeping track of the fixed point you started from and limiting the walk to no more than some fixed width of characters, and doing whatever it is you need to over-and-over again until you reach the end.
Help "Learn About Pointers"
Since in your comment below your question you mentioned you were "going to learn about pointers", start with the basics:
A pointer is simply a normal variable that holds the address of something else as its value. In other words, a pointer points to the address where something else can be found. Where you normally think of a variable holding an immediate values, such as int a = 5;, a pointer would simply hold the address where 5 is stored in memory, e.g. int *b = &a;.
To reference the value at the address held by a pointer you dereference the pointer by using the unary '*' character before the pointer name. E.g., b holds the address of a (e.g. b point to a), so to get the value at the address held by b, you simply dereference b, e.g. *b.
It works the same way regardless what type of object the pointer points to. It is able to work that way because the type of the pointer controls the pointer arithmetic, e.g. with a char * pointer, pointer+1 point to the next byte, for an int * pointer (normal 4-byte integer), pointer+1 will point to the next int at an offset 4-bytes after pointer. (so a pointer, is just a pointer.... where arithmetic is automatically handled by the type)
When you are dealing with strings in C, you can iterate from the beginning to the end of the string checking each character and stopping when you reach the nul-terminating character at the end of every string. This nul-character serves as a sentinel for the end of the string. You will see it represented as '\0' or just plain 0. Both are equivalent. The ASCII character '\0' has the integer value 0.
A simple example of walking a pointer may help cement the concept:
#include <stdio.h>
int main (void) {
char buf[] = "walk-a-pointer down buf", /* buffer */
*p = buf; /* initialize p to point to buffer */
/* dereference the pointer to get the character at that address */
while (*p) { /* while *p != 0, or (*p != '\0') */
putchar (*p); /* output each character */
p++; /* advance pointer to next char */
}
putchar ('\n'); /* then tidy up with a newline */
return 0;
}
Example Use/Output
$ ./bin/walkpointer
walk-a-pointer down buf

how to read text files

I am trying to extract key, values from a text file, but I am having trouble determining how to locate the end of a value. Here is a short snippet of the text file.
GIRRAFE: A tall spotted animal
LION: A short carnivore.
Prince: The son of a king.
Princess: The daughter of a king.
This is my code:
FILE *fp;
char line[20], word[20];
int i = 0, endind;
fp = fopen(file, "r");
if (fp==NULL){
printf("Error parsing the file\n");
exit(1);
}
while (!feof(fp)){
fgets(line, 100, fp);
for (i;i<strlen(line);i++){
if (line[i]=='.'){
endind = i;
}
}
for (i;i<endind;i++){
word[i] = line[i];
printf("%s\n",word);
}
}
The code is not very good as Im not able to get a value ending with a complete blank newline.
From the sample data, it looks like the key ends at the first '.'
in the string. Use strchr(3) to find it. But it looks like
the value, and the whole item, ends with two newlines. For
that you will need to write code to read a paragraph into a string.
For that, malloc(3) and realloc(3) will be useful. If you have
a known maximum size, you can of course use a fixed size buffer.
Break the problem into parts. First, read a paragraph, then find
where the key ends, then find where the value starts. Decide if the
two newlines are part of the value, and whether the period is part
of the key.
To read a paragraph, read in a line. If the line is empty, which you can determine with strcmp(line, "\n") then you're done reading the value,
and you can move on. Otherwise, append the line to the paragraph buffer.
Once you've got a whole paragraph as a single string, find the end of the
key with char *keyend = strchr(para, '.'), which will return a pointer to the '.' character. You can replace that character with a null (*keyend = 0)
and now para is a string with the key. Next advance the keyend pointer
to the first non-whitespace character. There are several ways to do that. At this point, keyend will now point to the value. Which
gives you para as a pointer to the key, and keyend as a pointer to the
value. Having that, you can update your hash table.
I would also check for errors along the way, and probably use separate
variables better named for the paragraph, key, and value. Trimming
off the trailing newline and other data validation is optional. For example, what if a paragraph doesn't contain a '.' character at all?
You are on the right track. The simple way to determine if you have an empty line (in your case) is:
fgets(line, 100, fp);
if (*line == '\n')
// the line is empty
(note: if (line[0] == '\n') is equivalent. In each case you are simply checking whether the 1st char in line is '\n'. Index notation of line[x] is equivalent to pointer notation *(line + x), and since you are checking the 1st character, (e.g. x=0), pointer notation is simply *line)
While you are free to use strtok or any other means to locate the 1st '.', using strchr() or simply using a pointer to iterate (walk-down) the buffer until you find the first '.' is probably an easier way to go. Your parsing flow should look something like:
readdef = 0; // flag telling us if we are reading word or definition
offset = 0; // number of chars copied to definition buffer
read line {
if (empty line (e.g. '\n')) { // we have a full word + definition
add definition to your list
reset readdef flag = 0
reset offset = 0
}
else if (readdef == 0) { // line with word + 1st part of definiton
scan forward to 1st '.'
check number of chars will fit in word buffer
copy to word buffer (or add to your list, etc..)
scan forward to start of definition (skip punct & whitespace)
get length of remainder of line (so you can save offset to append)
overwrite \n with ' ' to append subsequent parts of definition
strcpy to defn (this is the 1st part of definition)
update offset with length
set readdef flag = 1
}
else { // we are reading additional lines of definition
get length of remainder of line (so you can save offset to append)
check number of chars will fit in definition buffer
snprintf to defn + offset (or you can use strcat)
update offset with length
}
}
add final defintion to list
The key is looping and handling the different states of your input (either empty-line -- we have a word + full definition, readdef = 0 we need to start a new word + definition, or readdef = 1 we are adding lines to the current definition) You can think of this as a state loop. You are simply handling the different conditions (or states) presented by your input file. Note -- you must add the final definition after your read-loop (you still have the last definition in your definition buffer when fgets returns EOF)
Below is a short example working with your data-file. It simply outputs the word/definition pairs -- where you would be adding them to your list. You can use any combination of strtok, strchr or walking a pointer as I do below to parse the data file into words and definitions. Remember, if you ever find a problem where you can't make strtok fit your data -- you can always walk a pointer down the buffer comparing each character as you go and responding as required to parse your data.
You can also use snprintf or strcat to add the multiple lines of definitions together (or simply a pointer and a loop), but avoid strncpy, especially for large buffers -- it has a few performance penalties as it zeros the unused space every time.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXW 128 /* max chars in word or phrase */
#define MAXC 1024 /* max char for read buffer and definition */
int main (int argc, char **argv) {
int readdef = 0; /* flag for reading definition */
size_t offset = 0, /* offset for each part of definition */
len = 0; /* length of each line */
char buf[MAXC] = "", /* read (line) buffer */
word[MAXW] = "", /* buffer storing word */
defn[MAXC] = ""; /* buffer storing definition */
/* open filename given as 1st argument, (or read stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
return 1;
}
while (fgets (buf, MAXC, fp)) { /* read each line */
char *p = buf; /* pointer to parse word & 1st part of defn */
if (*buf == '\n') { /* empty-line, output definition */
defn[offset-1] = 0; /* remove trailing ' ' left for append */
printf ("defn: %s\n\n", defn);
readdef = 0; /* reset readdef flag - 0 */
offset = 0; /* reset offset - 0 */
}
else if (readdef == 0) { /* line contais word + 1st part of defn */
while (*p && *p != '.') /* find the first '.' */
p++;
if (p - buf + 1 > MAXW) { /* make sure word fits in word */
fprintf (stderr, "error: word exceeds %d chars.\n", MAXW - 1);
return 1;
}
snprintf (word, p - buf + 1, "%s", buf); /* copy to word */
printf ("word: %s\n", word); /* output word */
while (ispunct (*p) || isspace (*p)) /* scan to start of defn */
p++;
len = strlen (p); /* get length 1st part of defn */
if (len && p[len - 1] == '\n') /* chk \n, overwrite with ' ' */
p[len - 1] = ' ';
strcpy (defn, p); /* copy rest of line to defn */
offset += len; /* update offset (no. of chars in defn) */
readdef = 1; /* set readdef flag - 1 */
}
else { /* line contains next part of defn */
len = strlen (buf); /* get length */
if (len && buf[len - 1] == '\n') /* chk \n, overwite w/' ' */
buf[len - 1] = ' ';
if (offset + len + 1 > MAXC) { /* make sure it fits */
fprintf (stderr, "error: definition excees %d chars.\n",
MAXC - 1);
return 1;
}
snprintf (defn + offset, len + 1, "%s", buf); /* append defn */
offset += len; /* update offset */
}
}
if (fp != stdin) fclose (fp); /* close file if not stdin */
defn[offset-1] = 0; /* remove trailing ' ' left for append */
printf ("defn: %s\n\n", defn); /* output final definition */
return 0;
}
Example Input File
$ cat dat/definitions.txt
ACTE. A peninsula; the term was particularly applied by the ancients to
the sea-coast around Mount Athos.
ACT OF COURT. The decision of the court or judge on the verdict, or the
overruling of the court on a point of law.
TELEGRAPH, TO. To convey intelligence to a distance, through the medium
of signals.
TELESCOPIC OBJECTS. All those which are not visible to the unassisted
eye.
TELL OFF, TO. To divide a body of men into divisions and subdivisions,
preparatory to a special service.
TELL-TALE. A compass hanging face downwards from the beams in the cabin,
showing the position of the vessel's head. Also, an index in front of
the wheel to show the position of the tiller.
Example Use/Output
$ /bin/read_def <dat/definitions.txt
word: ACTE
defn: A peninsula; the term was particularly applied by the ancients to the sea-coast around Mount Athos.
word: ACT OF COURT
defn: The decision of the court or judge on the verdict, or the overruling of the court on a point of law.
word: TELEGRAPH, TO
defn: To convey intelligence to a distance, through the medium of signals.
word: TELESCOPIC OBJECTS
defn: All those which are not visible to the unassisted eye.
word: TELL OFF, TO
defn: To divide a body of men into divisions and subdivisions, preparatory to a special service.
word: TELL-TALE
defn: A compass hanging face downwards from the beams in the cabin, showing the position of the vessel's head. Also, an index in front of the wheel to show the position of the tiller.
Look things over and let me know if you have further questions.

How to sscanf only the last word from a string? [duplicate]

how would you get the last word of a string, starting from the '\0' newline character to the rightmost space? For example, I could have something like this where str could be assigned a string:
char str[80];
str = "my cat is yellow";
How would I get yellow?
Something like this:
char *p = strrchr(str, ' ');
if (p && *(p + 1))
printf("%s\n", p + 1);
In case you don't want to use 'strrchr' function, Here is the solution.
i = 0;
char *last_word;
while (str[i] != '\0')
{
if (str[i] <= 32 && str[i + 1] > 32)
last_word = &str[i + 1];
i++;
}
i = 0;
while (last_word && last_word[i] > 32)
{
write(1, &last_word[i], 1);
i++;
}
I would use function strrchr()
The best way to do this is to take advantage of existing solutions. One such solution (to a much more general problem) is Perl Compatible Regular Expressions, an open-source regular expression library for C. So, you can match the string "my cat is yellow" with the regular expression \b(\w+)$ (expressed in C as "\b(\w+)$") and keep the first captured group, which is "yellow."
(heavy sigh) The original code is WRONG in standard / K&R / ANSI C! It does NOT initialize the string (the character array named str)! I'd be surprised if the example compiled. What your program segment really needs is
if strcpy(str, "my cat is yellow")
{
/* everything went well, or at least one or more characters were copied. */
}
or, if you promised not to try to manipulate the string, you could use a char pointer to the hard-coded "my cat is yellow" string in your source code.
If, as stated, a "word" is bounded by a space character or a NULL character, then it would be faster to declare a character pointer and walk backwards from the character just before the NULL. Obviously, you'd first have to be sure that there was a non-empty string....
#define NO_SPACE 20
#define ZERO_LENGTH -1
int iLen;
char *cPtr;
if (iLen=strlen(str) ) /* get the number of characters in the sting */
{ /* there is at least one character in the string */
cPtr = (char *)(str + iLen); /* point to the NULL ending the string */
cPtr--; /* back up one character */
while (cPtr != str)
{ /* make sure there IS a space in the string
and that we don't walk too far back! */
if (' ' == *cPtr)
{ /* found a space */
/* Notice that we put the constant on the left?
That's insurance; the compiler would complain if we'd typed = instead of ==
*/
break;
}
cPtr--; /* walk back toward the beginning of the string */
}
if (cPtr != str)
{ /* found a space */
/* display the word and exit with the success code */
printf("The word is '%s'.\n", cPtr + 1);
exit (0);
}
else
{ /* oops. no space found in the string */
/* complain and exit with an error code */
fprintf(STDERR, "No space found.\n");
exit (NO_SPACE);
}
}
else
{ /* zero-length string. complain and exit with an error code. */
fprintf(STDERR, "Empty string.\n");
exit (ZERO_LENGTH);
}
Now you could argue that any non-alphabetic character should mark a word boundary, such as "Dogs-chase-cats" or "my cat:yellow". In that case, it'd be easy to say
if (!isalpha(*cPtr) )
in the loop instead of looking for just a space....

Resources