String manipulation library - c

EDIT: Have included only the relevant code
I have to manipulate an input string that looks like this
create /foo
create /foo/bar
write /foo/bar "text"
create /foo/bar/baz
And I've created this program (you don't need to look at all of it)
and the problem I have is with the function printAllFolders() which is called in the main() and it is defined right under the main() function. The problem must be in that function. Is it correct to pass the string in the struct path[] giving the parameter
comando->path ?
When I put that function in the main it does give me segmentation fault issue. The rest works just fine.
EDIT: just to be clear, the printAllFolders() does print all the strings in the path array, so I just need to pass the path[255] array, not the one with all two indexes.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct _command {
unsigned char command[10];
unsigned char path[255][255];
int pathLevels;
} command;
command* createCommandMul(unsigned char* str);
void printfAllFolders(unsigned char* stringhe, int lengthArray);
int main() {
command* comando = (command*) malloc(sizeof(command));
unsigned char* upPath = NULL;
unsigned char* allPath = NULL;
FILE* fp;
unsigned char* line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("/Users/mattiarighetti/Downloads/semplice.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
comando = createCommandMul(line);
upPath = upperPath(comando);
allPath = fullPath(comando);
printfAllFolders(comando->path, comando->pathLevels);
}
fclose(fp);
if (line)
free(line);
return 0;
}
void printfAllFolders(unsigned char* stringhe, int lengthArray) {
unsigned char* stringa = stringhe;
int length = lengthArray;
if (length == 0) printf("Cartella %s", stringa[length]);
for (int i = 0; i < length+1; i++) {
printf("Cartella %d %s\t", i, stringa[i]);
}
}
command* createCommandMul(unsigned char* str) {
unsigned char* c = str;
command* commandPointer = (command*) malloc(sizeof(command));
int commandIndex = 0;
int pathLevel = 0;
int pathIndex = 0;
/* Parte Comando */
while(*c != ' ' && commandIndex<10) {
commandPointer->command[commandIndex] = *c++;
commandIndex++;
}
commandPointer->command[commandIndex] = '\0';
while(*c == ' ') c++;
while(*c == '/') c++;
/* Parte Path*/
while(*c!='\0') {
if (*c == '/') {
commandPointer->path[pathLevel][pathIndex] = '\0';
pathLevel++;
pathIndex = 0;
c++;
} else {
commandPointer->path[pathLevel][pathIndex] = *c++;
pathIndex++;
}
}
commandPointer->path[pathLevel][pathIndex] = '\0';
commandPointer->pathLevels = pathLevel;
return commandPointer;
}

Perhaps there is some confusion about the difference between an array:
path[255][255]
and a pointer
unsigned char* stringhe
When passing the array -as- a pointer:
printfAllFolders(comando->path, ...
the printfAllFolders() function sees stringhe as a memory address where there happens to be an unsigned char stored. The printAllFolders() function does not know that stringhe actually points to a more complex object (array of unsigned char with [255][255] dimensions).
One fix to the question code is to change:
void printfAllFolders(unsigned char* stringhe, int lengthArray)
to the following:
void printfAllFolders(unsigned char stringhe[255][255], int lengthArray)
This passes additional information to the function needed to understand the more complex nature of stringhe.
Of course, the following line (again) removes this needed information:
unsigned char* stringa = stringhe;
Perhaps this line ^above^ should be eliminated?
Then change the line:
if (length == 0) printf("Cartella %s", stringa[length]);
to:
if (length == 0) printf("Cartella %s", stringhe[length]);
and then change line:
printf("Cartella %d %s\t", i, stringa[i]);
to:
printf("Cartella %d %s\t", i, stringhe[i]);

Related

How to shift letters to the right or left?

I am given a file with a string, for example "The United States was founded in *1776*". What I cannot figure out is how to shift letters one space to the left or right and have the letters wrap around. I am able to shift the letters from an a to b but not change its location within the word.
Example of this output would be:
"heT
nitedU
tatesS
asw
oundedf
ni
1776**"
In C, strings are stored as an array of chars in memory. Unlike C++ vectors, you can not insert or remove element within the array, you can only access their value or change their value.
If you declare a C string as follows:
char *myStr = "Fred";
It will be stored in memory as a five character array with the 5th character being the zero value which terminates a C string:
myStr[0] = 'F'
myStr[1] = 'r'
myStr[2] = 'e'
myStr[3] = 'd'
myStr[4] = 0
You need to design a for loop that copies each array element to the one before, while remembering that you need to save the one you are about to overwrite. In this example, it should result in the following copy operations being performed:
len = strlen(myStr);
saveCh = myStr[0];
myStr[0] = myStr[1];
myStr[1] = myStr[2];
myStr[2] = myStr[3];
myStr[3] = saveCh;
So now your job is to create a for loop that does that for any C string of any length.
So to rotate the chars within a C string to the left, you need to copy each char in the array at index i to previous array element i-1. The tricky part is to handle the wrap around properly when i=0 (in this example, you want to copy myStr[0] to myStr[3]. Now do that with a for loop.
You need to also understand that the last character of any C string is the null character (value zero), which terminates a C string. If you modify that element in the array, then your string will break. That is why saveCh is copied to myStr[3] and not to myStr[4].
void rotateStrLeftOneChar(char *myStr) {
// Always check for error and special cases first!
// If myStr is a NULL pointer, do nothing and exit
// If myStr is less than 2 chars, nothing needs to be done too.
if ((myStr != NULL) && (strlen(myStr)>1)) {
int len = strlen(myStr);
char saveCh = myStr[0];
int i = 0;
// Copy each char at index i+1 left to index i in the array
for(i=0; i<len-2; i++)
myStr[i] = myStr[i+1];
// The last character is special and is set to saveCh
myStr[len-1] = saveCh;
}
}
If you just need to output the letters to shift to the left and don't want to change original input then you can do:
#include <stdio.h>
#include <string.h>
void shiftletters(char * input, int i);
int main () {
char input[256];
int shift;
printf("Enter input : ");
scanf("%[^\n]s", input);
printf("Number of shifts : ");
scanf("%d", &shift);
shiftletters(input, shift);
return 0;
}
void shiftletters(char * input, int numshifts)
{
char str[256] = {'\0'};
char * delim = " \t";
char * pch = NULL;
int j, k, len, shifts;
if (input == NULL)
{
printf ("Invalid input\n");
return;
}
strcpy (str, input);
pch = strtok (str, delim);
while (pch != NULL)
{
len = strlen (pch);
if ((numshifts == len) || (len == 1))
{
printf ("%s\n", pch);
pch = strtok (NULL, delim);
continue;
}
if (len < numshifts)
shifts = numshifts % len;
else
shifts = numshifts;
for(j=shifts; j<len; j++)
printf("%c", pch[j]);
for(k=0; k<shifts; k++)
printf("%c", pch[k]);
printf("\n");
pch = strtok (NULL, delim);
}
}
The output of the program:
Enter input : The United States was founded in *1776*
Number of shifts : 1
heT
nitedU
tatesS
asw
oundedf
ni
1776**
like this
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
enum { L = -1, R = 1};
char *rotate(char word[], int dir){
size_t len = strlen(word);
char *temp = malloc(len + 1);
if(!temp){
perror("malloc");
exit(EXIT_FAILURE);
}
strcpy(temp, word);
for(char *src = temp; *src; ++src, ++dir){//or use memmove
word[(dir+len)%len] = *src;
}
free(temp);
return word;
}
int main(int argc, char *argv[]) {
FILE *fp = fopen("data.txt", "r");
if(fp == NULL){
perror("fopen");
exit(EXIT_FAILURE);
}
if(argc < 2){
fprintf(stderr, "Usage %s L|R...\n", argv[0]);
exit(EXIT_FAILURE);
}
char word[64];
while(fscanf(fp, "%63s", word)==1){
for(char *shift = argv[1]; *shift; ++shift){
int dir = *shift == 'L' ? L : R;
rotate(word, dir);
}
printf("%s\n", word);
}
fclose(fp);
}
using memmove version
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
enum { L = -1, R = 1};
char *rotate1(char word[], int dir){
size_t len = strlen(word);
if(len > 2){
char temp;
if(dir == L){
temp = word[0];
memmove(word, word+1, len-1);
word[len-1] = temp;
} else if(dir == R){
temp = word[len-1];
memmove(word+1, word, len-1);
word[0] = temp;
}
}
return word;
}
int main(int argc, char *argv[]) {
FILE *fp = fopen("data.txt", "r");
if(fp == NULL){
perror("fopen");
exit(EXIT_FAILURE);
}
if(argc < 2){
fprintf(stderr, "Usage %s L|R...\n", argv[0]);
exit(EXIT_FAILURE);
}
char word[64];
while(fscanf(fp, "%63s", word)==1){
for(char *shift = argv[1]; *shift; ++shift){
int dir = *shift == 'L' ? L : R;
rotate1(word, dir);
}
printf("%s\n", word);
}
}

How to get a pointer back from a void function after it iterates through a string pointer

I'm trying to write a code that goes through a given string using a pointer to parse it.
The original code I wrote worked fine but it was... redundant so I tried making it into a function call to make it more concise. Here is what i have:
char inputArray[300];
char buffer[300];
char username[100];
char password[100];
char name[100];
int i=0;
void repeat(char *to)
{
while(*to!='=')
{
to++;
}
}
void array(char *mm,char *tt)
{
i=0;
while(*tt!='+')
{
mm[i]=*tt;
tt++;
i++;
}
}
int main()
{
printf("give me the shit in this fashion: username=?+password=?+real=?\n");
scanf("%s",inputArray);
strcpy(buffer,inputArray);
char *tok=buffer;
repeat(tok);
tok++;
array(username,tok);
repeat(tok);
tok++;
array(password,tok);
tok++;
repeat(tok);
tok++;
array(name,tok);
}
For some reason it won't give me back the pointer array tok where it left off from the previous function call. why is that? it acts as if after calling it the pointer starts back from the beginning.
Functions receive copies of their arguments. Original arguments remain unaffected.
Giving something back has a special syntax in C: the return statement. Thus
char* repeat (char *to) // <- this function gives back a char*
{
while (*to != '=')
{
to++;
}
return to; // <- giving something back
}
Call it like this:
tok = repeat(tok);
Treat array in the same fashion.
Note 1, this function will result in *undefined behaviour if the string doesn't contain '='.
Note 2, it is also possible to pass a pointer to tok as the other answer suggests, but for sake of clarity it is only recommended to use this style when you need to return more than one thing from a function.
just change your repeat to this:
void repeat(char **to) {
while (**to != '=') {
(*to)++;
}
}
and call it like this:
repeat(&tok);
and always check for errors:
if (scanf("%299s", inputArray) != 1){
printf("incorrect input\n");
return 1;
}
and your sample code (and add check for errors in array and repeat to not go out of bounds):
#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>
char inputArray[300];
char buffer[300];
char username[300];
char password[300];
char name[300];
int i = 0;
void repeat(char **to) {
while (**to != '=') {
(*to)++;
}
}
void array(char *mm, char *tt){
i = 0;
while (*tt != '+') {
mm[i] = *tt;
tt++;
i++;
}
}
int main() {
printf("give me the shit in this fashion: username=?+password=?+real=?\n");
if (scanf("%299s", inputArray) != 1){
printf("incorrect input\n");
return 1;
}
inputArray[299] = 0;
strcpy(buffer, inputArray);
char *tok = buffer;
repeat(&tok);
tok++;
array(username, tok);
repeat(&tok);
tok++;
array(password, tok);
tok++;
repeat(&tok);
tok++;
array(name, tok);
}
and you may use this to not go out of bounds:
#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>
char* read_str(char *src, char *dst){
char *p, *q;
p = src;
while (*p != 0 && *p != '=') p++;
if (*p == 0) {
*dst = 0;
return NULL; // '=' not found
}
p++;
q = p;
while (*q != 0 && *q != '+') q++;
//if (*q == 0) return NULL;// '+' not found
while (p <= q) *dst++ = *p++;
dst--;
*dst = 0;
q++;
return q;
}
#define MAX_LEN 100
int main() {
char username[MAX_LEN];
char password[MAX_LEN];
char name[MAX_LEN];
char inputArray[MAX_LEN] = "username=Alex+password=123+real=Alex";
char *p = inputArray;
p = read_str(p, username);
if (p == NULL)return 1; // error
p = read_str(p, password);
if (p == NULL)return 1; // error
read_str(p, name);
printf("username: %s \n", username);
printf("password: %s \n", password);
printf(" name: %s \n", name);
}

How to create an array of strings given an array of pointers?

I am given a text file and I need to put it in a buffer and use get_lines to make an array of pointers after converting each line to a string. I am having trouble with just the get_lines function as I am getting a seg fault when run it.
Here's my code:
#include <stdlib.h>
#include <stdio.h>
int readfile(FILE *fp, char **cbuf);
char **get_lines(char *cbuf, int bufsize, int word);
int readword(FILE*tmp);
int main(int argc, char *argv[])
{
int i,bufsize, num_word;
char *cbuf;
char **lines;
FILE *fp;
FILE *tmp;
if( (fp=fopen(argv[1],"r")) == NULL)
{
perror("ERROR: bad/no filename");
exit(0);
}
tmp = fopen(argv[1],"r");
bufsize = readfile(fp,&cbuf);
num_word = readword(tmp);
lines = get_lines(cbuf, bufsize, num_word) ;
i=0;
while( lines[i] != NULL) {
printf("%i\t%s\n",i,lines[i]);
i++;
}
return 0;
}
int readfile(FILE *fp,char**cbuf)
{
int i;
char c;
fseek(fp, 0L, SEEK_END);
int bufsize = ftell(fp);
fseek(fp, 0L, SEEK_SET);
*cbuf = (char *)malloc(sizeof(char) * bufsize);
for (i = 0; i < bufsize; i++)
{
c = fgetc(fp);
(*cbuf)[i] = c;
}
return bufsize;
}
int readword(FILE*tmp)
{
int word = 0;
char c;
while((c = fgetc(tmp)) != EOF )
{
if (c == '\n')
word++;
}
return word;
}
char **get_lines(char *cbuf, int bufsize, int word)
{
int i = 0, j = 0, counter = 0;
char (*lines)[bufsize];
lines = (char**)malloc(sizeof(char*)*bufsize);
counter = cbuf;
for (i = 0; i < bufsize; i++)
{
if(cbuf[i] == '\n')
{
cbuf[i] == '\0';
counter = cbuf[i + 1];
j++;
}else
{
*lines[j] = &counter;
}
}
lines[word] == NULL;
return lines;
}
The violation causing the fault is not immediately obvious to me, can someone tell me what might be wrong in get_lines()?
This code is wrong:
char (*lines)[bufsize];
lines = (char**)malloc(sizeof(char*)*bufsize);
It allocates a pointer to an array of char. Then you malloc the wrong amount of space, cast to the wrong type, and write *lines[j] = &counter; which tries to store a pointer in a char.
You should get many compiler errors/warnings for the get_lines function. It's important to pay attention to such messages as they are telling you that something is wrong with your code. There's no point even starting to investigate a segfault until you have fixed all the errors and warnings.
See here for a great guide on how to debug your code; I suspect you would fail the rubber duckie test on the get_lines function.
Here is a fixed version (untested):
// Precondition: cbuf[bufsize] == '\0'
//
char **get_lines(char *cbuf, size_t bufsize, size_t num_lines)
{
// +1 for the NULL termination of the list
char **lines = malloc((num_lines + 1) * sizeof *lines);
size_t line = 0;
while ( line < num_lines )
{
lines[line++] = cbuf;
cbuf = strchr(cbuf, '\n');
if ( !cbuf )
break;
*cbuf++ = '\0';
}
lines[line] = NULL;
return lines;
}
In your existing code there is no room to write the null terminator for the last line; my advice is to make readfile actually malloc one extra byte and make sure that is set to 0.

String Search C program without using built-in functions

I have a problem in my C program. This is the String Search program. The problem is when I type the String aabaaacaamaad, the result comes NULL when I search for ab in it but it should not as ab is there in aabaaacaamaad. The same result also comes with am and ad which is right but why does it come with aabaaacaamaad? Code:
char* MyStrstr(char* pszSearchString, char* pszSearchWord);
int main(int argc, char* argv[])
{
char szTemp1[20] = {0};
char szTemp2[10] = {0};
char * pszTemp1 = NULL;
strcpy(szTemp1, "aabaaacaamaad");
strcpy(szTemp2, "aa");
pszTemp1 = MyStrstr(szTemp1, szTemp2);
printf("%s", pszTemp1);
getch();
return 0;
}
char* MyStrstr(char* pszSearchString, char* pszSearchWord)
{
int nFcount = 0;
int nScount = 0;
int nSearchLen = 0;
int nIndex = 0;
char* pszDelString = NULL;
if(pszSearchString == NULL || pszSearchWord == NULL) {
return NULL;
}
while(pszSearchWord[nSearchLen] != '\0') {
nSearchLen++;
}
if(nSearchLen <= 0){
return pszSearchString;
}
for(nFcount = 0; pszSearchString[nFcount] != '\0'; nFcount++) {
if(pszSearchString[nFcount] == pszSearchWord[nScount]) {
nScount++;
} else {
nScount = 0;
}
if(nScount == nSearchLen) {
nIndex = (nFcount - nScount) + 1;
pszDelString = pszSearchString + nIndex;
return pszDelString;
}
}
return NULL;
}
I see what your code is trying to do, you want to avoid a loop in a loop but however you're missing one thing. When a match fails you're not going back but still moving forward in pszSearchString while you should not. The result of this flaw is that with incomplete matches you skip characters. That's the reason why the strstr function originally uses a loop in a loop so for every character in pszSearchString there is an new loop to match with pszSearchWord. Here the original strstr.c file from BSD/Darwin:
char * strstr(const char *in, const char *str)
{
char c;
size_t len;
c = *str++;
if (!c)
return (char *) in; // Trivial empty string case
len = strlen(str);
do {
char sc;
do {
sc = *in++;
if (!sc)
return (char *) 0;
} while (sc != c);
} while (strncmp(in, str, len) != 0);
return (char *) (in - 1);
}

How do I read and store string of arbitrary length using malloc and realloc in C?

I have a structure
typedef struct store
{
char name[11];
int age;
} store;
and a main function(below is part of it):
int main()
{
int i=0;
int inputs;
char line[100];
char name[11];
char command[11];
store read[3000];
while(i < 3000 && gets(line) != NULL)
{
int tempage;
inputs = sscanf(line, "%10s %10s %d", command, name, &tempage);
if (inputs == 3)
{
if (strcmp(command, "register") == 0)
{
strncpy(read[i].name, name,10);
read[i].age = tempage;
i++;
....
I need to modify it so that it can read a line of arbitrary length, and store the name from the line which is also a string of arbitrary length using malloc and realloc.
How should I approach this?
What you need to do is read the line in smaller increments, and resize your buffer as you go.
As an example (not tested and not meaning to be particularly elegant, just an example):
char *readline(FILE *f)
{
char *buf = NULL;
size_t bufsz = 0, len = 0;
int keep_going = 1;
while (keep_going)
{
int c = fgetc(f);
if (c == EOF || c == '\n')
{
c = 0; // we'll add zero terminator
keep_going = 0; // and terminate the loop afterwards
}
if (bufsz == len)
{
// time to resize the buffer.
//
void *newbuf = NULL;
if (!buf)
{
bufsz = 512; // some arbitrary starting size.
newbuf = malloc(bufsz);
}
else
{
bufsz *= 2; // issue - ideally you'd check for overflow here.
newbuf = realloc(buf, bufsz);
}
if (!newbuf)
{
// Allocation failure. Free old buffer (if any) and bail.
//
free(buf);
buf = NULL;
break;
}
buf = newbuf;
}
buf[len++] = c;
}
return buf;
}
Change the name[11] to *name;
Allocate memory for that everytime using malloc.
By the way, register is a keyword in C language. You can't use it like you did !
I think what you're looking for is:
char* name;
name = (char*)malloc(sizeof(char));
This alternative approach is similar to #asveikau's, but economize on the use of malloc() by copying on the stack.
Please do not use this for homework answer.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
char * slurponeline(FILE *f, int s) {
const int size = 4096;
char buffer[size];
char * r;
int c,i=0;
while( i<size && (c = fgetc(f),c>=0 && c!='\n')) buffer[i++]=c;
if (0 == s && 0 == i) return 0;
r = (size==i)? slurponeline(f,s+size):malloc(s+i);
memcpy(r+s,buffer,i);
return r;
}
int main(int argc, char ** argv) {
FILE * f = fopen(argc>1?argv[1]:"a.out","rb");
char * a,*command,*commandend,*name,*nameend;
int age;
while (a = slurponeline(f,0)) {
char * p = a;
while (*p && *p == ' ') ++p; // skip blanks.
command = p;
while (*p && *p != ' ') ++p; // skip non-blanks.
commandend = p;
while (*p && *p == ' ') ++p; // skip blanks.
name = p;
while (*p && *p != ' ') ++p; // skip non-blanks.
nameend = p;
while (*p && *p == ' ') ++p; // skip blanks.
age = atoi(p);
*commandend=0;
*nameend=0;
printf("command: %s, name: %s, age: %d\n",command,name,age);
free(a);
}
}

Resources