in today task i had to implement the function "my_split" that is based on pointers and accessing addresses, I'm having a little bit of trouble with "catching" all of the content from the file into the output.
this is my function:
void my_split(const char *source, char *first, char *second, const char delim){
int ree = 1;
while(*source != '\n'){
if(*source == delim){
ree = 0;
*source++;
}
else{
if(ree == 1){
*first++ = *source++;
}
else {
*second++ = *source++;
}
}
}
*first = '\0';
*second = '\0';
}
Main function:
int main(void){
int max_n = 200;
char source[max_n];
char strA[max_n];
char strB[max_n];
int T;
scanf("%d%*c", &T);
for(int i = 0; i < T; i++){
fgets (source, max_n, stdin);
my_split(source, strA, strB, ';');
printf("First: %s\n", strA);
printf("Second: %s\n", strB);
}
}
^^^ teacher gave us this one.
TXT FILE:
2
2345.454;6737.98
this is the line;splitted by semicolon
My output is:
First:
Second:
First: 2345.454
Second: 6737.98
The desired output is:
First: 2345.454
Second: 6737.98
First: this is the line
Second: splitted by semicolon
I'm trying to make above function, but It didn't workout, well it works half-succesfull
Your function seem to work. Try it like this...
#include <stdio.h>
void my_split(const char *, char *, char *, const char);
int main() {
FILE* fp;
fp = fopen("data.txt", "r");
if (NULL == fp) {
printf("file can't be opened \n");
return 0;
}
char source[100];
while (fgets(source, 100, fp) != NULL) {
char first[100] = "", second[100] = "";
my_split(source, first, second, ';');
printf("First: %s\n", first);
printf("Second: %s\n", second);
}
// Closing the file
fclose(fp);
return 0;
}
void my_split(const char *source, char *first, char *second, const char delim){
int ree = 1;
while(*source != '\n'){
if(*source == delim){
ree = 0;
*source++;
}
else{
if(ree == 1){
*first++ = *source++;
}
else {
*second++ = *source++;
}
}
}
*first = '\0';
*second = '\0';
}
It outputs:
First: 2
Second:
First: 2345.454
Second: 6737.98
First: this is the line
Second: splitted by semicolon
Related
I have csv file with below format :
name,birthmonth,country,hobby
jack,jan,england,soccer
roben,july,germany,soccer
emma,dec,china,tennis
yannick,sep,france,music
alex,nov,england,cricket
thomas,apr,germany,tennis
mike,oct,netherlands,cycling
michelle,feb,france,poetry
yui,mar,japan,coding
feng,jun,china,reading
I want to parse this file using C, and put all the lines with same country name in a consecutive manner i.e shown below:
name,birthmonth,country,hobby
jack,jan,england,soccer
alex,nov,england,cricket
roben,july,germany,soccer
thomas,apr,germany,tennis
emma,dec,china,tennis
feng,jun,china,reading
yannick,sep,france,music
michelle,feb,france,poetry
mike,oct,netherlands,cycling
yui,mar,japan,coding
So far, I have tried this code below, however not able to match things properly and proceed further:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<fcntl.h>
#include<string.h>
int main (int argc, char **argv) {
//int line;
char line[200];
char *inputFile = argv[1];
FILE *input_csv_file;
char a,b,c,d,e;
input_csv_file = fopen(inputFile, "rt");
if(input_csv_file ==0) {
printf("Can not open input file \n");
}
else {
//while((line = fgetc(input_csv_file)) != EOF) {
while(fgets(line, sizeof line, input_csv_file) != NULL) {
printf ("line = %s\n", line);
if(sscanf(line, "%s,%s,%s,%s,%s", a,b,c,d,e)) {
//if(sscanf(line, "%[^,], %[^,], %[^,], %[^,], %[^,]", a,b,c,d,e)) {
printf("d=%s\n",d);
}
}
}
return 0;
}
I am a newbie in C/C++. Any help would be much appreciated
Thanks.
I could write the code to get the required output. Below is the code:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<fcntl.h>
#include<string.h>
int main(int argc, char ** argv)
{
struct filedata {
char nation[8];
char content[50];
};
char line[100];
char *inputFile = argv[1];
FILE *input_csv_file;
int iter = 0, c;
char * tok;
int count = 0;
char ch;
char country[] = "country";
char header_line[50];
input_csv_file = fopen(inputFile, "rt");
//count line numbers of the input csv
for(ch = getc(input_csv_file); ch!= EOF; ch=getc(input_csv_file))
if(ch == '\n')
count = count + 1;
fclose(input_csv_file);
count = count -1;
struct filedata * record[count];
input_csv_file = fopen(inputFile, "rt");
if(input_csv_file == 0)
{
printf("Can not open input file\n");
} else
{
while(fgets(line, sizeof line, input_csv_file) != NULL)
{
//printf("-- line = %s\n", line);
int s_line = sizeof line;
char dup_line[s_line];
strcpy(dup_line, line);
int h = 0;
int s_token;
tok = strtok(line, ",");
while(tok != NULL)
{
h++;
if(h == 3)
{
s_token = sizeof tok;
break;
}
tok = strtok(NULL, ",");
}
// skipping the line having column headers
if(compare_col(tok, country) == 0) {
strcpy(header_line, dup_line);
continue;
}
iter++;
c = iter - 1;
record[c] = (struct filedata*)malloc(sizeof(struct filedata));
strcpy(record[c]->nation, tok);
strcpy(record[c]->content, dup_line);
} //while
struct filedata * temp;
FILE * fptr;
fptr = fopen("nation_csv.txt", "w");
if(fptr == NULL)
{
printf("Error in opening the file to write\n");
exit(1);
}
// sorting the arr of struct nation wise
for(iter=1; iter < count; iter++)
for(c =0 ; c < count -1; c++) {
if(strcmp(record[c]->nation, record[c+1]->nation) > 0) {
temp = record[c];
record[c] = record[c+1];
record[c+1] = temp;
}
}
for(iter=0; iter < count; ++iter)
{
if(iter == 0) {
fprintf(fptr, "%s", header_line);
continue;
}
fprintf(fptr, "%s", record[iter]->content);
}
fclose(fptr);
}
fclose(input_csv_file);
}
int compare_col(char a[], char b[] )
{
int c = 0;
while(a[c] == b[c]) {
if(a[c] == '\0' || b[c] == '\0')
break;
c++;
}
if(a[c] == '\0' && b[c] == '\0')
return 0;
else
return -1;
}
Thanks for all your inputs. Any further inputs to make it better are much appreciated.
Thanks
can you advice me? I have a string from a file. When i see the string on my console, i need to write the word on which i want to change, and output the result in another file. For example: "Hello my girl" the word i want change "girl" on another word "boy". I can use the library
Can you advice me the algorithm which helps me to change the word?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char my_string[256];
char* ptr;
FILE *f;
if ((f = fopen("test.txt", "r"))==NULL) {
printf("Cannot open test file.\n");
exit(1);}
FILE *out;
if((out=fopen("result.txt","w"))==NULL){
printf("ERROR\n");
exit(1);
}
fgets (my_string,256,f);
printf ("result: %s\n",my_string);
ptr = strtok (my_string," ");
while (ptr != NULL)
{
printf ("%s \n",ptr);
ptr = strtok (NULL," ");
}
char old_word [10];
char new_word [10];
char* ptr_old;
char* ptr_new;
printf ("Enter your old word:\n");
ptr_old= gets (old_word);
printf ("Your old word:%s\n",old_word);
printf ("Enter new old word:\n");
ptr_new = gets (new_word);
printf ("Your new word:%s\n",new_word);
fclose(f);
fclose(out);
return 0;
}
i tried to split inputting string into words. Now its dead end.
This code will help you. you have to pass 4 args at runtime.
./a.out "oldword" "newword" "file name from take the old word" "file name where to copy"
$ ./a.out girl boy test.txt result.txt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int args, char *argv[4])
{
FILE *f1;
FILE *f2;
char *strings=0;
char *newstrings=0;
char *token=NULL;
strings=(char *)malloc(1000);
newstrings=(char *)malloc(1000);
if((strings==NULL)||(newstrings==NULL))
{
printf("Memory allocation was not successfull.");
return 0;
}
if(args<4)
{
puts("Error: Not enough input parameters");
puts("Usage: ./change <oldword> <newword> <infile> <newfile>");
return 0;
}
f1=fopen(argv[3],"r");
f2=fopen(argv[4],"w");
if(f1==NULL)
{
puts("No such file exists");
return 0;
}
while(fgets(strings,1000,f1)!=NULL)
{
if(strstr(strings,argv[1])!=NULL)
{
token=strtok(strings,"\n\t ");
while(token!=NULL)
{
if(strcmp(token,argv[1])==0)
{
strcat(newstrings,argv[2]);
strcat(newstrings," ");
}
else
{
strcat(newstrings,token);
strcat(newstrings," ");
}
token=strtok(NULL,"\n\t ");
}
}
else
{
strcpy(newstrings,strings);
}
fputs(newstrings,f2);
}
free(strings);
free(newstrings);
printf("New file <%s> generated!\n",argv[4]);
fclose(f1);
fclose(f2);
return 0;
}
You can use a function like the shown function in the demonstrative program below
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char * replace(const char *s, const char *src, const char *dsn)
{
size_t n = 0;
size_t src_len = strlen(src);
size_t dsn_len = strlen(dsn);
for (const char *p = s; (p = strstr(p, src)) != NULL; p += src_len)
{
n++;
}
char *result = malloc(strlen(s) + n * (src_len - dsn_len) + 1);
const char *p = s;
char *t = result;
if (n != 0)
{
for (const char *q; (q = strstr(p, src)) != NULL; p = q + src_len)
{
memcpy(t, p, q - p);
t += q - p;
memcpy(t, dsn, dsn_len);
t += dsn_len;
}
}
strcpy(t, p);
return result;
}
int main( void )
{
char s[] = " the girl and boy are relatives";
char *p = replace(s, "girl", "boy");
puts(s);
puts(p);
free(p);
}
The program output is
the girl and boy are relatives
the boy and boy are relatives
#include <stdio.h>
#include <string.h>
int main ()
{
char file_path[40] = { 0 }, stf[255] = { 0 }, rtf[255] = { 0 }, str[255] = { 0 };
FILE* file = NULL;
FILE *e_f;
if((e_f=fopen("result.txt","w"))==NULL){
printf("ERROR\n");
exit(1);
}
do
{
printf("Enter file path: ");
fgets(file_path, 40, stdin);
file_path[strlen(file_path) - 1] = '\0';
file = fopen(file_path, "r+");
}
while(file == NULL);
printf("Enter text to find: ");
fgets(stf, 255, stdin);
stf[strlen(stf) - 1] = '\0';
printf("Enter text to replace: ");
fgets(rtf, 255, stdin);
rtf[strlen(rtf) - 1] = '\0';
while(fgets(str, 255, file) != NULL)
{
char* tmp_ptr = strstr(str, stf);
while(tmp_ptr != NULL)
{
char tmp_str[255];
strcpy(tmp_str, tmp_ptr + strlen(stf));
strcpy(str + strlen(str) - strlen(tmp_ptr), rtf);
strcat(str, tmp_str);
tmp_ptr = strstr(str, stf);
}
printf("%s", str);
}
fclose(file);
fclose(e_f);
return 0;
}
That was i need. Thanks everybody for helping!
I did a function:
#include <stdio.h>
#include <string.h>
#define MAX 50
void Change (char x[], char cx, char nu){
int i;
for(i=0;i<strlen(x);i++) {
if (x[i]==cx){
x[i] = nu;
}
}
}
int main () {
char str[MAX];
char ch;
char new;
printf("Insert the string\n");
scanf("%s",str);
printf("Insert the word that you want to change\n");
scanf(" %c",&ch);
printf("the new word\n");
scanf(" %c",&new);
Change(str, ch, new);
printf("The new word is %s\n",str );
return 0;
}
I have a file which I have already tokenized but I need to store each token in an array to later use as parameters. How would i go about doing this?
// Read in File //
FILE *fp;
char buffer[100];
fp = fopen(params, "r");
printf("Here is filename...");
printf("%s\n", params);
fseek(fp, 0, SEEK_END);
//byte_size = ftell(fp);
rewind(fp);
if (fgets(buffer,sizeof(buffer),fp) != NULL)
{
char*p, *b;
b = buffer;
printf("parsing %s", buffer);
while ((p = strsep(&b, ",")) != NULL)
{
printf("param: %s\n",p);
}
}
fclose(fp);
Using linked list and convert it to array later may be good because we don't know how many tokens are there.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strsep(char **stringp, const char *delim);
typedef struct node_tag {
char *str;
struct node_tag* next;
} list_node;
list_node* create_node(const char *str) {
list_node* n = malloc(sizeof(list_node));
if (n == NULL) exit(1);
if (str == NULL) {
n->str = NULL;
} else {
n->str = malloc(sizeof(char) * (strlen(str) + 1));
if (n->str == NULL) exit(1);
strcpy(n->str, str);
}
n->next = NULL;
return n;
}
int main(void) {
const char *params = "dummy";
FILE *fp;
char buffer[100];
list_node *head = NULL;
list_node **tail = &head;
unsigned int count = 0;
unsigned int i;
char **array;
fp = stdin;//fopen(params, "r");
printf("Here is filename...");
printf("%s\n", params);
fseek(fp, 0, SEEK_END);
//byte_size = ftell(fp);
rewind(fp);
if (fgets(buffer,sizeof(buffer),fp) != NULL)
{
char*p, *b;
b = buffer;
printf("parsing %s", buffer);
while ((p = strsep(&b, ",")) != NULL)
{
printf("param: %s\n",p);
*tail = create_node(p);
tail = &(*tail)->next;
count++;
}
}
array = malloc(sizeof(char*) * count);
if (array == NULL) return 1;
for (i = 0; i < count && head != NULL; i++) {
list_node *next = head->next;
array[i] = head->str;
// Don't free(head->str) because it is used
free(head);
head = next;
}
for (i = 0; i < count; i++) {
printf("array[%u] = %s\n", i, array[i]);
}
for (i = 0; i < count; i++) free(array[i]);
free(array);
//fclose(fp);
return 0;
}
You can simply use array if you know the number of tokens.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strsep(char **stringp, const char *delim);
#define ARRAY_SIZE 8
int main(void) {
const char *params = "dummy";
FILE *fp;
char buffer[100];
char *array[ARRAY_SIZE];
int array_count = 0;
int i;
fp = stdin;//fopen(params, "r");
printf("Here is filename...");
printf("%s\n", params);
fseek(fp, 0, SEEK_END);
//byte_size = ftell(fp);
rewind(fp);
if (fgets(buffer,sizeof(buffer),fp) != NULL)
{
char*p, *b;
b = buffer;
printf("parsing %s", buffer);
while ((p = strsep(&b, ",")) != NULL)
{
printf("param: %s\n",p);
if (array_count < ARRAY_SIZE)
{
array[array_count] = malloc(sizeof(char) * (strlen(p) + 1));
strcpy(array[array_count], p);
array_count++;
}
}
}
for (i = 0; i < array_count; i++) {
printf("array[%u] = %s\n", i, array[i]);
}
for (i = 0; i < array_count; i++) free(array[i]);
//fclose(fp);
return 0;
}
When I gdb the program, it says something is wrong with strcpy, but I do not know why.
Thanks.
The program requires me to read an input file, find the course abbreviation, the course description, the number of credit hours, and the professor name.
Also, I am trying to read the credit hours from the file, which are on the same line as the course. I am trying to only get the credit hours that are on the same line as the course, but it instead prints every number as a credit hour.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 20
typedef struct courses{
char *abbr;
char *name;
int credits;
char *prof;
struct courses *next;
}courses;
int isAbbr(char *string);
int isName(char *string);
int isCredit(char *string);
int isProf(char *string);
courses *readfile(FILE *);
courses *create_course(char *abbr, char *name, int credits, char *prof);
courses *create_list(courses *, courses *);
int main(int argc, char **argv)
{
if (argc != 2)
{
printf("Inadequate amount of arguments.\n");
return 0;
}
FILE *fp = fopen(argv[1], "r");
if (fp == NULL)
{
printf("File cannot be opened.\n");
return 0;
}
courses* head = NULL;
head = readfile(fp);
int choice = 0;
while (choice != 3)
{
printf("\nSelect your option below:\n1-Register for a Course\n2-See my total\n3-Exit\nChoice: ");
scanf("%d",&choice);
}
return 0;
}
courses *readfile(FILE *fp)
{
courses *head, *entry;
head = entry = NULL;
char *abbr = malloc(MAX);
char *namep = malloc(MAX);
namep = "hello";
char *prof = malloc(MAX);
int credit;
int credflag = 0;
int nameFlag = 0;
int profFlag = 0;
int credits = 0;
char line[MAX];
while (fgets(line, MAX - 1, fp) != NULL)
{
if (line[strlen(line) - 1] == '\n')
{
line[strlen(line) - 1] = '\0';
}
char* token = strtok(line," ,\t");
while (token != NULL)
{
if (isAbbr(token) == 1)
{
abbr = token;
credflag = 1;
}
if (isName(token) == 1)
{
credflag = 1;
}
if (isCredit(token) == 1)
{
if(credflag == 1)
{
credits = atoi(token);
credflag = 0;
}
}
if (isProf(token)== 1)
{
if(nameFlag == 1) //print names, reset name flag = 0
{
entry = create_course(abbr, namep, credits, token);
head = create_list(entry,head);
nameFlag = 0;
}
else
{
namep = malloc(sizeof(char));
strcpy(namep, token);
nameFlag = 1;
}
}
else
{
nameFlag = 0;
}
token = strtok(NULL," ,\t");
}
}
}
courses *create_course(char *abbr, char *name, int credits, char *prof)
{
courses *entry = malloc(sizeof(courses));
entry->abbr=(char*)malloc(sizeof(char)*256);
strcpy(entry->abbr, abbr);
entry->name=(char*)malloc(sizeof(char)*256);
strcpy(entry->name, name);
entry->abbr=(char*)malloc(sizeof(char)*256);
strcpy(entry->prof, prof);
entry->credits = credits;
entry->next = NULL;
return entry;
}
courses *create_list(courses *head, courses *entry)
{
if (head == NULL)
{
return entry;
}
courses* curr = head;
while (curr->next != NULL)
{
curr = curr->next;
}
curr->next = entry;
return head;
}
int isProf(char *string)
{
int length = strlen(string);
int i;
if (isupper(string[0]))
{
for (i=1; i<length; i++)
{
if (islower(string[i]))
{
continue;
}
else
{
return 0;
}
}
return 1;
}
}
int isCredit(char *string)
{
int n;
int nfields = sscanf(string, "%d", &n);
if (nfields == 1 && n > 0)
{
return 1;
}
return 0;
}
int isName(char *string)
{
return 1;
}
int isAbbr(char *string)
{
int length = strlen(string);
if (length == 8 && string[4] == '-')
{
printf(" %s\n",string);
return 1;
}
return 1;
}
Just focus on strcpy:
char *namep = malloc(MAX);
namep = "hello";
here you just lose what you malloc for namep, use strcpy or something you want.
namep = malloc(sizeof(char));
strcpy(namep, token);
here you just malloc 1 char for namep, but strcpy auto add NULL terminator, so unless token is "", you overflow namep.
And every strcpy in create_course(), you just malloc 256 and strcpy, what if size of abbr, name, prof > 255? check size or use strncpy().
I am working on a program that includes a selection of code which is "supposed" to filter a string in order to prevent non-alphanumeric characters (except for underscores) from being passed further on into the program. The part that does this worked fine when I tested it before implementing it in the main program (as shown below), but when I run it now the output is just repeated a bunch of times until there is a segmentation fault, and i cannot for the life of me figure out what is causing this to happen, so if anyone could help with this problem I would very much appreciate it, thanks! also for ease of seeing where this is implemented in the main program, i have taken a screenshot of where it is located in the main code http://i.imgur.com/dKLgx.png, and my apologies for the long post length
austin#Ruby:~/cprac$ ./words
[hel123_lo]
testing code that worked
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
int i;
char *p;
char stg[] = "hel123*^_l!o";
char output[200] = {0x00};
int index = 0;
p = stg;
while( *p )
{
if (isalnum(*p) || *p == '_')
{
output[index++] = *p;
}
p++;
}
printf("[%s]\n", output);
return 0;
}
main code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#ifndef max
#define max(a, b) ((a)>(b))? (a) : (b)
#endif
long GetFileSize(FILE *fp){
long fsize = 0;
fseek(fp,0,SEEK_END);
fsize = ftell(fp);
fseek(fp,0,SEEK_SET);//reset stream position!!
return fsize;
}
char *lastline(char *filepath){
FILE *fp;
char buff[4096+1];
int size,i;
long fsize;
if(NULL==(fp=fopen(filepath, "r"))){
perror("file cannot open at lastline");
return NULL;
}
fsize= -1L*GetFileSize(fp);
if(size=fseek(fp, max(fsize, -4096L), SEEK_END)){
perror("cannot seek");
exit(0);
}
size=fread(buff, sizeof(char), 4096, fp);
fclose(fp);
buff[size] = '\0';
i=size-1;
if(buff[i]=='\n'){
buff[i] = '\0';
}
while(i >=0 && buff[i] != '\n')
--i;
++i;
return strdup(&buff[i]);
}
int main(int argc, char *argv[], char *envp[]){
char *last;
char *name;
char field_x[128];
char field_y[128];
char field_z[128];
char field_world[128];
char field_cause[128];
char field_killer[128];
name = getenv("MCEXEC_PLAYERNAME");
char *filename;
char *p;
char *ispvp;
// m
int i;
char *f;
char output[200] = {0x00};
int index = 0;
filename = malloc(sizeof "/home/minecraft/freedonia/playerdata/deathlog-.txt" - 1 + strlen(name) + 1);
if (!filename) exit(EXIT_FAILURE);
snprintf(filename,4096,"/home/minecraft/freedonia/playerdata/deathlog- %s.txt",name);
last = lastline(filename);
if( last != NULL ) {
printf( "%s\n", last );
sscanf(last, "%*[^:]:%*[^:]:%*[^:]:%127[^:]:", field_x);
sscanf(last, "%*[^:]:%*[^:]:%*[^:]:%*[^:]:%127[^:]:", field_y);
sscanf(last, "%*[^:]:%*[^:]:%*[^:]:%*[^:]:%*[^:]:%127[^:]:", field_z);
sscanf(last, "%*[^:]:%*[^:]:%*[^:]:%*[^:]:%*[^:]:%*[^:]:%127[^:]:", field_world);
sscanf(last, "%*[^:]:%*[^:]:%*[^:]:%*[^:]:%*[^:]:%*[^:]:%*[^:]:%127[^:]:", field_cause);
p = strchr(field_cause, '_');
printf( "X coord: %s\n", field_x);
printf( "Y coord: %s\n", field_y);
printf( "Z coord: %s\n", field_z);
printf( "World: %s\n", field_world);
printf( "Cause: %s\n", field_cause);
while (p != NULL) {
ispvp = "true";
// printf ("found at %d\n",p - field_cause + 1);
sscanf(field_cause, "%*[^_]_%128[^_]_", field_killer);
printf( "%s\n", field_killer);
f = field_cause;
while( *f )
{
if (isalnum(*f) || *f == '_')
{
output[index++] = *f;
}
f++;
}
printf("[%s]\n", output);
// p = strchr(p + 1, '_');
}
}
// printf("\"%s\"\n", last);
free(last);
return 0;
}
while (p != NULL) {
ispvp = "true";
// printf ("found at %d\n",p - field_cause + 1);
sscanf(field_cause, "%*[^_]_%128[^_]_", field_killer);
printf( "%s\n", field_killer);
f = field_cause;
while( *f )
{
if (isalnum(*f) || *f == '_')
{
output[index++] = *f;
}
f++;
}
printf("[%s]\n", output);
// p = strchr(p + 1, '_');
}
P never changes in this block, so it will always be != NULL.