How to read csv files using 2d Array - c++

I have done using the single dimensional array,Want to convert it using two dimensional array.As i am a beginner, I am not able to do it.Please help me in converting this program using two dimensional array and thank you in advance
#include<stdio.h>
#include<string.h>
FILE *file;
char str[20];
char buffer[128];
char *token;
char *a[20],b[20];
int main ()
{
int i=0;
printf("\n Enter the file name:");
scanf("%s",&str);
file=fopen(str,"r");
if(file != NULL)
{
while(fgets(buffer,128,file) != NULL)
{
token = strtok(buffer,",");
while(token != NULL)
{
a[i]=strdup(token);
printf("%s\t",a[i]);
token = strtok(NULL,",");
i++;
}
}
}
else
{
printf("\n the file name you have entered doesnot exist");
}
fclose(file);
return 0;
}

#include<stdio.h>
#include<string.h>
int e,f;
FILE *file;
char buffer[128];
char *token;
int n,m;
char *a[10][10];
int i=0,j;
void find_keyword()
{
while(fgets(buffer,128,file) != NULL)
{
token = strtok(buffer,",");
j=0;
while(token != NULL)
{
a[i][j]=strdup(token);
printf("a[%d][%d]=%s\t",i,j,a[i][j]);
token = strtok(NULL,",");
j++;
}
i++;
}
}
void main ()
{
printf("Enter the values of m and n?\n");
scanf("%d",&m);
scanf("%d",&n);
file=fopen("D:/test.csv","r");
printf("File Open\n");
if(file != NULL)
{
find_keyword();
}
else
{
printf("\n the file name you have entered doesnot exist");
}
fclose(file);
printf("\nFile Closed\n");
}

Related

Creating a history function for a Unix Shell

Here is what my program currently looks like. I have to add history functionality that gets stored in a file 'mysh.history'. Currently I expect my output to simply append each user command in my shell to the file.
first line of output
first line of output
It only appends the first input into the shell instance. I think my problem lies with my understanding of the fork() process but I'm not sure what is going on. Any suggestions?
#define MYSH_BUFFERSIZE 64
#define MYSH_DELIM " \t\n"
fstream file;
// custom function declarations
int mysh_exit(char **args);
int mysh_add_history(char **args);
int mysh_history(char **);
char byebye[] = "byebye";
char exit_program[] = "exit";
char history[] = "history";
// contains names of all custom shell commands implemented
char *lookup_str[] = {byebye, exit_program, history};
// holds references to all commands in lookup_str[]
// order or commands must match each other
int (*lookup_func[])(char **) = {
&mysh_exit,
&mysh_exit,
&mysh_history
};
/* custom shell commands implementations BEGIN*/
// Without the argument, it prints out the recently typed commands (with their
// arguments), in reverse order, with numbers
// If the argument ā€œ-cā€ is passed, it clears the list of recently typed commands.
void clear_history()
{
file.close();
file.open("mysh.history", ios::trunc);
}
int mysh_add_history(char *line)
{
// if exists then append to the history
if (access("mysh.history", F_OK) == 0)
{
file.open("mysh.history", ios::app);
}
// otherwise create mysh.history and start writing
else
{
file.open("mysh.history", ios::out);
}
file << line << "\n";
return 0;
}
int mysh_history(char **)
{
return 0;
}
int mysh_exit(char **args)
{
return 0;
}
int num_commands()
{
return sizeof(lookup_str) / sizeof(char *);
}
/* custom shell functions END*/
/* main shell processes BEGIN*/
// returns the tokens (arguments) array after tokenizing line from mysh_read_line()
char **mysh_split_args(char *line)
{
int buffer_size = MYSH_BUFFERSIZE;
int current_pos = 0;
char **tokens = (char **)malloc(buffer_size * sizeof(char *));
char *tok;
if (!tokens)
{
printf("mysh: memory allocation error\n");
exit(EXIT_FAILURE);
}
tok = strtok(line, MYSH_DELIM);
while (tok != NULL)
{
tokens[current_pos] = tok;
current_pos++;
if (current_pos >= buffer_size)
{
buffer_size += MYSH_BUFFERSIZE;
tokens = (char **)realloc(tokens, buffer_size * sizeof(char *));
if (!tokens)
{
printf("mysh: memory allocation error\n");
exit(EXIT_FAILURE);
}
}
tok = strtok(NULL, MYSH_DELIM);
}
tokens[current_pos] = NULL;
return tokens;
}
// mysh_read_line allocates MYSH_BUFFER_SIZE of memory to the intial buffer
// it reallocates memory as needed with getLine() function
// returns line to be processed and tokenized by mysh_split_args()
char *mysh_read_line(void)
{
char *line = NULL;
size_t buffersize = 0;
// getLine() also needs to check for EOF after in the case of text files being read.
if (getline(&line, &buffersize, stdin) == -1)
{
if (feof(stdin))
{
exit(EXIT_SUCCESS);
}
else
{
printf("failed to read line\n");
exit(EXIT_FAILURE);
}
}
return line;
}
// args passed comes from mysh_split_args()
int mysh_launch_process(char **args)
{
pid_t pid;
pid_t wpid;
int state;
pid = fork();
// if we enter child process
if (pid == 0)
{
if (execvp(args[0], args) == -1)
{
printf("error in mysh\n");
}
exit(EXIT_FAILURE);
}
// forking failed
else if (pid < 0)
{
printf("error in mysh\n");
}
else
{
// if we enter parent process
do
{
wpid = waitpid(pid, &state, WUNTRACED);
} while (!WIFEXITED(state) && !WIFSIGNALED(state));
}
return 1;
}
// calls mysh_launch_process() and handles programs being called
int mysh_execute(char **args)
{
int i;
if (args[0] == NULL)
{
return 1;
}
for (i = 0; i < num_commands(); i++)
{
if (strcmp(args[0], lookup_str[i]) == 0)
{
if (strcmp(args[0], "history") == 0 && strcmp(args[1], "-c"))
{
clear_history();
}
return (*lookup_func[i])(args);
}
}
return mysh_launch_process(args);
}
void mysh_loop(void)
{
char *line;
char **args;
int state;
do
{
printf("# ");
line = mysh_read_line();
mysh_add_history(line);
args = mysh_split_args(line);
state = mysh_execute(args);
free(line);
free(args);
} while (state);
}
int main(int argc, char **argv)
{
// run main program loop
mysh_loop();
file.close();
return EXIT_SUCCESS;
}
/* main shell processes END*/```

i have a program that takes input a string that's called search which is the target and i want to search in the csv file if the "search" is there

#include <stdio.h>
#include <string.h>
void myFgets(char str[], int n);
int main(int argc, char** argv)
{
if (argc < 2)
{
printf("Usage: csv <csv file path>\n");
return 1;
}
else
{
char ch = ' ', search[100], dh = ' ';
int row = 1;
printf("Enter value to search: ");
myFgets(search, 100);
FILE* fileRead = fopen(argv[1], "r");
if (fileRead == NULL)
{
printf("Error opening the file!\n");
return 1;
}
while ((ch = (char)fgetc(fileRead)) != EOF)
{
char str[100];
int i = 0, pos = ftell(fileRead);
while ((dh = (char)fgetc(fileRead)) != ',')
{
str[i] = dh;
i++;
}
fseek(fileRead, pos + 1, SEEK_SET);
if (strstr("\n", str) != NULL)
{
row++;
}
if (strstr(search, str) != NULL)
{
printf("Value was found in row: %d\n", row);
break;
}
}
}
getchar();
return 0;
}
/*
Function will perform the fgets command and also remove the newline
that might be at the end of the string - a known issue with fgets.
input: the buffer to read into, the number of chars to read
*/
void myFgets(char* str, int n)
{
fgets(str, n, stdin);
str[strcspn(str, "\n")] = 0;
}
in line 39 im getting an error but idk why it seems like im doing everything fine
im trying to loop through the rows and split them by the ',' so i could check if search == to it but its not wokring
im using function strstr to compare 2 strings with each other it works fine and all but the only problem is at the dh
i did fseek after the dh so i dont write in the wrong place in the ch loop
You forgot to terminate the string.
while ((dh = (char)fgetc(fileRead)) != ',')
{
str[i] = dh;
i++;
}
str[i] = '\0'; /* add this to terminate the string */
Also it looks like if (strstr(search, str) != NULL) should be if (strstr(str, search) != NULL) to search for the value to search from the contents of the file.

How gets size of char[] when i read from a text file

I'm reading a .txt file. I need to read at most 254 characters into my char* buffer, so I did this:
char *buffer = new char[255];
***Some Code***
if (!feof(fichero))
{
if (fgets(buffer, 254, fichero) != NULL)
{
How do get the size of the buffer read? Right now I'm using a manual method to find '\n' and use its position as the size. But is there a better way?
My code for now:
char *buffer = new char[255];
int tamanio;
***more code***
if (!feof(fichero))
{
if (fgets(buffer, 254, fichero) != NULL)
{
//printarCadena(buffer);
tamanio = limpiarBuffer(buffer);
printf("Tamanio buffer: %i \n", tamanio);
int Gestor::limpiarBuffer(char* buffer)
{
int i;
for(i = 0; i < int(strlen(buffer));i++)
{
if(buffer[i] == '\n')
return i;
}
return int(strlen(buffer) - 1);
}
Edit: I`ve to use Char*, University vibes
Edit2: I've to read line by line, if line ve more than 255 characteres, i read as 2 or more lines
int getSize(char* buffer)
{
int i;
for(i = 0; i < int(strlen(buffer));i++)
{
if(buffer[i] == '\n')
return i;
}
return strlen(buffer);
}
By now no other way to do with char*

Printing array of char pointers

I am trying to read two lines from a file using array of pointers. However, I am not getting anything on screen. I have tried searching online, but could not solve the problem. Here is my code that I have written using Netbeans on mac.
int main(int argc, char** argv) {
FILE *fp;
char *points[50];
char c;
int i=0;
fp=fopen("/Users/shubhamsharma/Desktop/data.txt","r");
if(fp==NULL)
{
printf("Reached here");
fprintf(stderr," Could not open the File!");
exit(1);
}
c=getc(fp);
while(c!=EOF)
{
*points[i]=c;
c=getc(fp);
i++;
}
for(int i=0;*points[i]!='\0';i++)
{
char d=*points[i];
printf("%c",d);
if(*(points[i+1])==',')
{
i=i+1;
}
}
return (EXIT_SUCCESS);
}
char *points[50];
Is not what you want, this is an array of 50 pointers to char.
If you want an array of pointers to char[50] you need:
char (*points)[50];
points = malloc(sizeof(*points) * 2);
Also note that fgets is prefered to get a line from a file
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char (*points)[50];
points = malloc(sizeof(*points) * 2);
if (points == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
fp = fopen("/Users/shubhamsharma/Desktop/data.txt", "r");
if (fp == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
fgets(points[0], sizeof(*points), fp);
fgets(points[1], sizeof(*points), fp);
fclose(fp);
printf("%s", points[0]);
printf("%s", points[1]);
free(points);
return 0;
}

How to read a string file from second line in C?

This code reads characters in a file and calculates length of characters. How i can read from second line and ignore read from first line?
this is part of my code:
int lenA = 0;
FILE * fileA;
char holder;
char *seqA=NULL;
char *temp=NULL;
fileA=fopen("d:\\str1.fa", "r");
if(fileA == NULL) {
perror ("Error opening 'str1.fa'\n");
exit(EXIT_FAILURE);
}
while((holder=fgetc(fileA)) != EOF) {
lenA++;
temp=(char*)realloc(seqA,lenA*sizeof(char));
if (temp!=NULL) {
seqA=temp;
seqA[lenA-1]=holder;
}
else {
free (seqA);
puts ("Error (re)allocating memory");
exit (1);
}
}
cout<<"Length seqA is: "<<lenA<<endl;
fclose(fileA);
Make a counter of how many \n you have seen,and when ==1 goto read from 2nd line.
int line=0;
while((holder=fgetc(fileA)) != EOF) {
if(holder == '\n') line++;
if(holder == 1) break; /* 1 because count start from 0,you know */
}
if(holder == EOF) {
//error:there's no a 2nd
}
while((holder=fgetc(fileA)) != EOF) {
// holder is contents begging from 2nd line
}
You can make it more simple by using fgets():
Make one call and ignore it(by don't discard the result-value,for error-checking);
Make second call, and begging reading from this.
NOTE: I'm considering C language here.
There is a tiny mistakes about the last answer.
I corrected and here is my code:
#include <stdio.h>
#include <stdlib.h>
#define TEMP_PATH "/FILEPATH/network_speed.txt"
int main( int argc, char *argv[] )
{
FILE *fp;
fp=fopen(TEMP_PATH, "r");
char holder;
int line=0;
while((holder=fgetc(fp)) != EOF) {
if(holder == '\n') line++;
if(line == 1) break; /* 1 because count start from 0,you know */
}
if(holder == EOF) {
printf("%s doesn't have the 2nd line\n", fp);
//error:there's no a 2nd
}
while((holder=fgetc(fp)) != EOF && (holder != '\n' )) {
putchar(holder);
}
fclose(fp);
}