Copy string from given character

1

I'm developing a C program, which will work with 02 files .txt

The first file is a report, which comes out directly from the system, and there are information such as item code, location and quantity in stock, this information is on the same line ...

The product code takes up at most the first 14 characters of the string, and I used the following code to remove it from .txt :

memcpy( cod, &c[0], 14);
cod[15] = '
memcpy( cod, &c[0], 14);
cod[15] = '%pre%';
';

However, in the continuation of the line, I have more information that I wanted to allocate in other variables, to pass them to the second .txt file, which I will use as output for a Zebra printer.

How do I access characters from position 15 onwards, and copy them to a variable?

    
asked by anonymous 02.01.2017 / 23:35

2 answers

6

You are on the right path. Did not start taking position 0? As you want to get from position 15 onwards, use it. Whichever way you go to the end, you should take the sizeof of the whole text and subtract the 15 that you want to discard.

#include <stdio.h>
#include <string.h>

int main(void) {
    char texto[] = "1234567890abcdefghijklm";
    int posicao = 15;
    int final = sizeof(texto) - posicao;
    char parte[final];
    memcpy(parte, &texto[posicao], final);
    printf("%s", parte);
}

See running on ideone .

If the string is not the known size at compile time, you would need to use a strlen() to find out its size. Or strnlen() if you can not trust that the string is well formed . p>

Instead of &texto[posicao] you can use texto + posicao since texto is the address of string , you just need to add the element number in it. In fact, [] is only syntactic sugar for this arithmetic pointer operation.

    
02.01.2017 / 23:55
1

I suggest using sscanf . Example Assuming Fixed Length Fields 14,20,20:

#include <stdio.h>

int main(){
 char texto[] = "cod 1234567890 Joaquim da Silva    933322232";
 char a[30], b[30],c[30];
 if( sscanf(texto,"%14[^\n]%20[^\n]%[^\n]" ,a,b,c) == 3)
    printf("cod='%s' nome='%s' tel='%s'\n",a,b,c);
 return 0;
}

Running gives:

cod='cod 1234567890' nome=' Joaquim da Silva   ' tel=' 933322232'
    
03.01.2017 / 11:05