i have this data
27a1bc
thats supposed to be a data recieved from serial communication/uart.
the question is, is there anyway i could separate this data without delimeter? i need the data change to this
27
a1
bc
is there anyway i could do this without delimeter/strtok?
here is my code, im stuck.
#include <stdio.h>
#include <stdlib.h>
char usart[] = "27a1bc";
int main(void) {
// your code goes here
scanf("%c", usart[1]);
scanf("%c", usart[0]);
return 0; }
You can use a pointer to an array of 3 char's (2 + 1 for the trailing NUL) and memcpy in a loop:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char usart[] = "27a1bc";
int main(void)
{
size_t i, n = sizeof usart / 2;
char (*token)[3];
token = calloc(n, sizeof *token);
if (token == NULL) {
perror("calloc");
exit(EXIT_FAILURE);
}
for (i = 0; i < n; i++) {
memcpy(token[i], usart + (i * 2), 2);
puts(token[i]);
}
free(token);
return 0;
}
Related
I have currently made this much of the code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#define STRSIZE 21
struct PInven{
int count;
struct PItem{
char name[STRSIZE];
int amount;
}Pitem;
}Pinven;//this needs to be an output file
int ReadInProduce (){
//read in file and check to see if the file exist or not.
FILE * PinFile = fopen("produce.txt","r");
if (PinFile == NULL){
printf("ERROR: WRONG FILE");
}
else{
printf("I did it!!\n");
}
//assigning the value gotten into the struct variable(but need to maybe change this since it needs to be an output)
fscanf(PinFile,"%d",&Pinven.count);
printf("%d\n", Pinven.count);
int i;
for(i =0; i <Pinven.count; i++){
fscanf(PinFile,"%20s %d",Pinven.Pitem.name, &Pinven.Pitem.amount);
printf("%s %d\n",Pinven.Pitem.name, Pinven.Pitem.amount);
}
//making an array to hold the variables
//FILE * PoutFile = fopen("produce_update.txt","w");
fclose(PinFile);
return 0;
}
From there I want to get the file that is read to the structs to be printed out into an array so that later on I can make a function that will be able to compare to the to it.
Basically a store management system. Where the file of the inventory is read in and compared to the file that is store and return a new value for the amount of produce now either left or gained.
10 //number of items that will be stored in the store
apple 19
banana 31
broccoli 9
...
In general, it's a really bad idea to include header information in the file about the number of entries in the file. You want to be able to do stream processing, and that will be more difficult if you need that meta-data. More importantly, it is important to understand how to write the code so that you don't need it. It's not really that difficult, but for some reason people avoid it. One simple approach is just to grow the array for each entry. This is horribly inefficient, but for the sake of simplicity, here's an example that expects the file not not include that first line:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <limits.h>
#define STRSIZE 128
struct PItem{
char name[STRSIZE];
int amount;
};
struct PInven{
int count;
struct PItem *PItem;
};
static void
grow(struct PInven *p)
{
p->PItem = realloc(p->PItem, ++p->count * sizeof *p->PItem);
if( p->PItem == NULL ){
perror("out of memory");
exit(1);
}
}
int
ReadInProduce(struct PInven *P, const char *path)
{
FILE * PinFile = fopen(path, "r");
if( PinFile == NULL ){
perror(path);
exit(1);
}
char fmt[64];
int max_len;
max_len = snprintf(fmt, 0, "%d", INT_MAX);
snprintf(fmt, sizeof fmt, "%%%ds %%%dd", STRSIZE - 1, max_len - 1);
grow(P);
struct PItem *i = P->PItem;
while( fscanf(PinFile, fmt, i->name, &i->amount) == 2 ){
i += 1;
grow(P);
}
P->count -= 1;
fclose(PinFile); /* Should check for error here! */
return P->count;
}
int
main(int argc, char **argv)
{
struct PInven P = {0};
char *input = argc > 1 ? argv[1] : "produce.txt";
ReadInProduce(&P, input);
struct PItem *t = P.PItem;
for( int i = 0; i < P.count; i++, t++ ){
printf("%10d: %s\n", t->amount, t->name);
}
}
As an exercise for the reader, you should add some error handling. At the moment, this code simply stops reading the input file if there is bad input. Also, it would be a useful exercise to do fewer reallocations.
you should change Structure of PInven to it can save a dynamic array of Pitem with a Pitem pointer.
tested :
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define STRSIZE 21
typedef struct {
char name[STRSIZE];
int amount;
} Pitem;
struct PInven {
int count;
Pitem *pitem;
} Pinven; // this needs to be an output file
int main() {
// read in file and check to see if the file exist or not.
FILE *PinFile = fopen("produce.txt", "r");
if (PinFile == NULL) {
printf("ERROR: WRONG FILE");
} else {
printf("I did it!!\n");
}
// assigning the value gotten into the struct variable(but need to maybe
// change this since it needs to be an output)
fscanf(PinFile, "%d", &Pinven.count);
Pinven.pitem = (Pitem *)malloc(sizeof(Pitem) * Pinven.count);
printf("%d\n", Pinven.count);
int i;
for (i = 0; i < Pinven.count; i++) {
fscanf(PinFile, "%20s %d", Pinven.pitem[i].name,
&Pinven.pitem[i].amount);
// printf("%s %d\n",Pinven.pitem[i].name, Pinven.pitem[i].amount);
}
for (i = 0; i < Pinven.count; i++) {
printf("%s %d\n", Pinven.pitem[i].name, Pinven.pitem[i].amount);
}
// making an array to hold the variables
// FILE * PoutFile = fopen("produce_update.txt","w");
fclose(PinFile);
// remember free
free(Pinven.pitem);
return 0;
}
i searched online everywhere but i was unable to find a solution that i could implement in my code, i have some limiting factors to take in accounts, the biggest one is: i cannot use pointers to do this, second one is that i cannot edit before the comment
what i have to do is look for the SEC_B sequence in the adn1 string then save the position of it into a int array to then print it something like this:
Found sequence GTC in: 20 62 69 159 167 196
and yes i did count them manually
i have to do the same with the other sequences, but that doesn't matter as long is i can get it working with one, i can then make it work with all the others
so this is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SECUENCIA0 "TGGCGTTTGCAGATTACTGCGTCCCTCACAAGGGTGTGAA"
#define SECUENCIA1 "GCTGTGCATTCGCGGCACAAGAGTCCCGGGTCCCTGTAGC"
#define SECUENCIA2 "TTCACCATCCTGTTGTACCTATCAAACCTACCTACAGCTT"
#define SECUENCIA3 "AGTGAAGGATTATGCGATTGGCGAGCATAGTACCGGCCCG"
#define SECUENCIA4 "TCACACCGTCTCATTGGTGGCCGACCTTGGAACTCCGTCA"
#define SEC_B "GTC"
#define SEC_D "GAT"
#define SEC_K "GT"
int main()
{
char adn1[201];
adn1[0]='\0';
strcat(adn1,SECUENCIA0);
strcat(adn1,SECUENCIA1);
strcat(adn1,SECUENCIA2);
strcat(adn1,SECUENCIA3);
strcat(adn1,SECUENCIA4);
//edit from here
return 0;
}
this solution doesn't involve any explicit pointers (no * anywhere) and doesn't edit the line above the comment, i managed to come up with this solution thanks to the answer of zazz (which he deleted for some reson), here's how i've done it
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SECUENCIA0 "TGGCGTTTGCAGATTACTGCGTCCCTCACAAGGGTGTGAA"
#define SECUENCIA1 "GCTGTGCATTCGCGGCACAAGAGTCCCGGGTCCCTGTAGC"
#define SECUENCIA2 "TTCACCATCCTGTTGTACCTATCAAACCTACCTACAGCTT"
#define SECUENCIA3 "AGTGAAGGATTATGCGATTGGCGAGCATAGTACCGGCCCG"
#define SECUENCIA4 "TCACACCGTCTCATTGGTGGCCGACCTTGGAACTCCGTCA"
#define SEC_B "GTC"
#define SEC_D "GAT"
#define SEC_K "GT"
int main()
{
char adn1[201];
adn1[0]='\0';
strcat(adn1,SECUENCIA0);
strcat(adn1,SECUENCIA1);
strcat(adn1,SECUENCIA2);
strcat(adn1,SECUENCIA3);
strcat(adn1,SECUENCIA4);
//edit below here
printf("---- Búsqueda de secuencias B, D y K dentro del adn1 ------\n");
int PosicionesB[20];
int bs = 0;
int i, l1, l2;
l1 = strlen(adn1);
l2 = strlen(SEC_B);
for(i = 0; i < l1 - l2 + 1; i++) {
if(strstr(adn1 + i, SEC_B) == adn1 + i) {
PosicionesB[bs] = i;
bs++;
i = i + l2 -1;
}
}
printf("Found sequence GTC in:");
for(int i = 0; i < bs;i++){
printf(" %d",PosicionesB[i]);
}
return 0;
}
It's as simple as this:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
void print_indices_substr(const char *str, const char *substr)
{
char *pstr;
printf("Indices: { ");
for (pstr = (char *)str; (pstr = strstr(pstr, substr)) != NULL; pstr = &pstr[1])
printf("%lu, ", (uintptr_t)pstr - (uintptr_t)str);
printf("}\n");
}
Basically, the function strstr returns a pointer to the first occurrence of 'substr' in 'str' or NULL if no occurrence was found. We can use this pointer in a for loop, and the index will be pstr - str, as you can see in the function above. Example:
int main()
{
const char my_string[] = "ABCDABCD";
print_indices_substr(my_string, "ABCD");
return 0;
}
Output:
Indices: { 0, 4, }
I am trying to simulate map-reduce. I have a problem with thread management and passing by reference. When sending a single character it works, but sending a whole struct gives me a segmentation fault.
Each sentence in text.txt is separated by a newline (\n).
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <fcntl.h>
#include <stdbool.h>
typedef struct sentencetype
{
char *sentence;
int length;
}sentencetype;
void *map(void *ptr){
sentencetype allQueuesSingle = *((sentencetype*) ptr);
printf("%c", allQueuesSingle.sentence[0]);
//why doesnt this print the first letter in each line
pthread_exit(NULL);
}
int main(void) {
char letter;
int mapthreadsSize = 0, sentenceSTRSize = 0;
pthread_t *mapthreads = malloc(sizeof(pthread_t));
sentencetype *sentenceSTR;
int fd = open("text.txt", O_CREAT | O_RDONLY, 0777);
sentenceSTRSize = 1;
sentenceSTR = malloc(sentenceSTRSize * sizeof(sentencetype));
sentenceSTR[0].sentence = malloc(sizeof(char));
sentenceSTR[0].length = 0;
while (read(fd, &letter, 1)){
sentenceSTR[sentenceSTRSize-1].length++;
sentenceSTR[sentenceSTRSize-1].sentence = realloc(
sentenceSTR[sentenceSTRSize-1].sentence,
sentenceSTR[sentenceSTRSize-1].length * sizeof(char));
sentenceSTR[sentenceSTRSize-1].sentence[sentenceSTR[sentenceSTRSize-1].length-1] = letter;
if(sentenceSTR[sentenceSTRSize-1].sentence[sentenceSTR[sentenceSTRSize-1].length-1] == '\n'){
//send sentence
mapthreadsSize++;
mapthreads = realloc(mapthreads, mapthreadsSize * sizeof(pthread_t));
pthread_create(&mapthreads[mapthreadsSize-1], NULL, map, &sentenceSTR[sentenceSTRSize-1]);
sentenceSTRSize++;
sentenceSTR = realloc(sentenceSTR, sentenceSTRSize * sizeof(sentencetype));
sentenceSTR[sentenceSTRSize-1].sentence = malloc(sizeof(char));
sentenceSTR[sentenceSTRSize-1].length = 0;
}
}
//send last sentence
mapthreadsSize++;
mapthreads = realloc(mapthreads, mapthreadsSize * sizeof(pthread_t));
pthread_create(&mapthreads[mapthreadsSize-1], NULL, map, &sentenceSTR[sentenceSTRSize-1]);
for (int i = 0; i < mapthreadsSize; i++) {
pthread_join(mapthreads[i], NULL);
}
}
realloc() is allowed to reseat the array. So the pointer that your threads are holding are potentially getting invalidated when you realloc sentenceSTR.
A fairly straightforward way to fix this would be to not create the pthreads until you are done processing the entire file.
Fairly new to C, I am trying to read a file of multiple words using bash indirection, and put the words into a string array. The end of the file is marked with a -1.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void init(char* words[]);
int main(int argc,char *argv[]){
char* words[400000];
init(words);
int i = 0;
do{
printf("%s",words[i]);
i++;
}while(!strcmp(words[i],"-1"));
}
void init(char* words[]){ // initializes array
int i = 0;
do{
fgets(words[i],1024,stdin);
i++;
}while(!strcmp(words[i],"-1"));
}
This gives me a segmentation fault, if any other information is needed I'm more than happy to provide it.
If I guessed correctly, '400000' means the max lines the user can input. But the default size of stack on Windows OS is 1M, sizeof(void*) * 400000 = 1,600,000...
The other thing is that you have not allocated memory for every line.
So, I try to correct your code like this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LINE 4000 // '400000' is really too big!
void init(char* words[]);
int main(int argc,char *argv[]){
char* words[MAX_LINE];
memset(words, 0 , sizeof(words));
init(words);
int i = 0;
do{
printf("%s",words[i]);
delete words[i];
words[i] = nullptr;
i++;
}while(!strcmp(words[i],"-1"));
}
void init(char* words[]){ // initializes array
int maxLen = 1024;
int i = 0;
do{
words[i] = new char[maxLen];
memset(words[i], 0, maxLen);
fgets(words[i], maxLen, stdin);
i++;
}while(!strcmp(words[i],"-1") && i < MAX_LINE);
}
I have for example "asd" and I want it to be randomized to DAS, DSA, SAD, you know. How can I code this? Tried a few solutions but It didnt really work.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
int main()
{
printf("type in the word\n");
char haslo[128];
scanf("%s", haslo);
char set[128];
char hasloa[128];
strcpy(set, haslo);
unsigned int Ind = 0;
srand(time(NULL) + rand());
int len = strlen(set);
while(Ind < len)
{
hasloa[Ind++] = set[rand()%62];
}
hasloa[len] = '\0';
printf("%s", hasloa);
return 0;
}
Change 62 inside the while loop to "len"