Printing array of char pointers - c++

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;
}

Related

Cant copy the whole text file to char array

I am trying to copy a whole text file into char array using fstream but even upon increasing the size of the array it reads the text file to same limit .i am bount to save it in a char array and it will be good if it is not a dynamic one ??? any solution please ...
// smallGrams.cpp : Defines the entry point for the console application.
//
//#include "stdafx.h"
#include<iostream>
using namespace std;
#include<string>
#include<fstream>
void readInput(const char* Path);
void removePunctucationMarks();
void removeSpacing();
void insertDots();
char * getText();
void generateUnigrams();
void generateBigrams();
void generateTrigrams();
double validateSentance(string str);
string sentenceCreation(int position);
int main()
{
char *path="alice.txt";
readInput(path);
return 0;
}
void readInput(const char* Path)
{
ifstream infile;
infile.open(Path);
if(!infile.fail())
cout<<"File opened successfully"<<endl;
else
cout<<"File failed to open"<<endl;
int arrSize=100000000;
char *arr=new char[arrSize];
int i=0;
while(!infile.eof()&&i<arrSize)
{
infile.get(arr[i]);
i++;
}
arr[i-1]='\0';
for(short i=0;i<arrSize&&arr[i]!='\0';i++)
{
cout<<arr[i];
}
}
This is a C style solution that works. It checks the file size and then allocate the necessary memory for the array and reads all the content of the file in one call. The fread() call returns the number of bytes you requested or an error has ocurred (check fread() reference)
# include <cstring>
# include <cstdlib>
# include <cstdio>
int main(int argc, char *argv[]) {
char *data;
int data_len;
FILE *fd;
fd = fopen ("file.txt", "r");
if (fd == NULL) {
// error
return -1;
}
fseek (fd , 0 , SEEK_END);
data_len = ftell (fd);
rewind (fd);
data = (char *) malloc ((data_len + 1) * sizeof (char));
memset (data, data_len + 1, NULL);
if (fread (data, sizeof (char), data_len, fd) != data_len) {
// error
return -1;
}
printf ("%s\n", data);
fclose (fd);
free (data);
return 0;
}
Here with a simple doubling method...
#include<iostream>
#include<string>
#include<fstream>
#include <cstdint>
#include <cstring>
using namespace std;
void readInput(const char* Path)
{
ifstream infile;
infile.open(Path);
if(!infile.fail())
cout<<"File opened successfully"<<endl;
else{
cout<<"File failed to open"<<endl;
return;
}
int capacity=1000;
char *arr=new char[capacity];
char *temp;
int i=0;
while(infile >> arr[i])
{
i++;
if ( i >= capacity ) {
temp = new char[capacity*2];
std::memcpy(temp , arr, capacity);
delete [] arr;
arr = temp;
capacity *=2;
}
}
}
int main()
{
char *path="alice.txt";
readInput(path);
return 0;
}
The error could when you read and display the array content using the for loop and not on reading the data from file.
Use int instead of short in for loop, as short can increment upto 32768, only.

How to read csv files using 2d Array

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");
}

programming c threaded io

Hi what i want to do is read from a text file do something to the text and write it back out to a file. I need it to be threaded so all 3 party can run at the same time. I am trying to use a buffer to read in to and a buffer to write out from but cant work it out.
My code :
#include <stdio.h>
#include <pthread.h>
char inBuf[1000];
//char outBuf[];
void *readerFun(void *meg){
char *inputFile;
FILE *input_ptr;
inputFile = (char *) meg;
input_ptr = fopen(inputFile, "r");
if(input_ptr == NULL){
printf("%s\n", inputFile);
printf("input file not working\n");
return;
}
while(!feof(input_ptr)){
fscanf(input_ptr, "%s", &inBuf);
sleep(1);
// printf("%s\n", &inBuf );
// printf("test _____________\n" );
}
return NULL;
}
void *modifierFun(void *meg){
//char c;
//while((c = getc(inBuf) != EOF)){
//strcat(outBuf, c);
//}
//}
return NULL;
}
void *writerFun(void *meg){
char *outFile;
FILE *output_ptr;
outFile = (char *) meg;
output_ptr = fopen(outFile, "a");
while(inBuf != NULL){
printf("%s\n", inBuf );
fprintf(output_ptr, "%s", inBuf);
}
return NULL;
}
int
main (int argc, char **argv){
pthread_t reader, modifier, writer;
char *meg = argv[1];
char *meg2 = argv[2];
int ret1, ret2, ret3;
ret1 = pthread_create(&reader, NULL, readerFun, (void *) meg);
ret2 = pthread_create(&modifier, NULL, modifierFun, (void *) meg);
ret3 = pthread_create(&writer, NULL, writerFun, (void *) meg2);
pthread_join(reader, NULL);
pthread_join(modifier, NULL);
pthread_join(writer, NULL);
return 0;
}
Would be a big help is someone could point me down the right road. I have looked all over the net and cant really find what im looking for.

Source File Compiling and Command

I am new to programming and was able to compile the following source code in C++ using Visual Studio, but when I put the command that came with the source file foo < RTP300.cfg > text.cfg nothing happens. This command is supposed to generate a text file from a router configuration file. Where should the RTP300.cfg file that the command is pointing to be located? Any other info that can help would be greatly appreciated. Thanks!
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int decode(unsigned char);
int
decode(unsigned char ch)
{
ch = ~((ch << 2) | ((ch & 0xC0) >> 6));
if (ch) {
if (isprint(ch)) {
return ch;
} else {
return ' ';
}
}
return '\n';
}
int
main(int argc, char *argv[])
{
int ch;
FILE *fp;
if (argc < 2) {
fp = stdin;
} else {
if (NULL == (fp = fopen(argv[1], "r"))) {
fprintf(stderr, "Error: Cannot open file %s\n", argv[1]);
exit(EXIT_FAILURE);
}
}
while (EOF != (ch =fgetc(fp))) {
fputc(decode(ch), stdout);
}
return EXIT_SUCCESS;
}

stack check fail in sha-1 c++

I'm having a __stack_chk_fail in the main thread.
I have no idea why is this happening?
I got the codes from this website:
http://www.packetizer.com/security/sha1/
Im trying to add a function to compute the digest of a file using the example.
.h file
#include <stdio.h>
#include <string>
std::string digestFile( char *filename );
.cpp file
std::string SHA1::digestFile( char *filename )
{
Reset();
FILE *fp = NULL;
if (!(fp = fopen(filename, "rb")))
{
printf("sha: unable to open file %s\n", filename);
return NULL;
}
char c = fgetc(fp);
while(!feof(fp))
{
Input(c);
c = fgetc(fp);
}
fclose(fp);
unsigned message_digest[5];
if (!Result(message_digest))
{ printf("sha: could not compute message digest for %s\n", filename); }
std::string hash;
for (int i = 0; i < 5; i++)
{
char buffer[8];
int count = sprintf(buffer, "%08x", message_digest[i]);
if (count != 8)
{ printf("converting unsiged to char ERROR"); }
hash.append(buffer);
}
return hash;
}
__stack_chk_fail occurs when you write to invalid address.
It turns out you do:
char buffer[8];
int count = sprintf(buffer, "%08x", message_digest[i]);
C strings are NUL-terminated. That means that when sprintf writes 8 digits, it adds 9-th char, '\0'. But buffer only has space for 8 chars, so the 9-th goes past the end of the buffer.
You need char buffer[9]. Or do it the C++ way with std::stringstream, which does not involve any fixed sizes and thus no risk of buffer overrun.