My file include 1 word in every line(i know the number of the line).I want to read random line, store it's adress in pointer and return to main function. There is 1 warning (19|warning: return makes pointer from integer without a cast [-Wint-conversion]|) and when i run the program it dont prints anything.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char *word(char *file, char *str);
int main() {
char *str;
printf("%s",word("words.txt",str));
}
char *word(char *file, char *str) {
int end, loop, line;
FILE *fd = fopen(file, "r");
if (fd == NULL) {
printf("Failed to open file\n");
return -1;
}
srand(time(NULL));
line = rand() % 100 + 1;
for (end = loop = 0; loop < line; ++loop) {
if (0 == fgets(str, sizeof(str), fd)) {
end = 1;
break;
}
}
if (!end)
return (char*)str;
fclose(fd);
}
Related
I am trying to mimic a basic encryption algorithm. I try to read the encrypted data file and look for each corresponding value in a JRB tree (simple key-value pair in my case) which is basically filled from the ".key" file and then write it to another file.
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "fields.h"
#include <cJSON.h>
#include "jrb.h"
void decrypt();
int main(int argc, char **argv)
{
decrypt();
return 0;
}
void decrypt()
{
IS is_input;
FILE *fp;
int i, j;
char *buffer = 0;
char *str = 0;
long length;
FILE *f = fopen ("data/.key", "rb");
cJSON *json;
JRB b, tmp;
b = make_jrb();
tmp = make_jrb();
is_input = new_inputstruct("data/encrypted");
if (is_input == NULL) {
perror("Error: ");
exit(1);
}
fp = fopen("data/decrypted.txt", "w+");
if (fp < 0) { perror("Error: "); exit(1); }
if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = malloc (length);
if (buffer)
{
fread (buffer, 1, length, f);
}
fclose (f);
}
if (buffer)
{
json = cJSON_Parse(buffer);
cJSON *current_element = NULL;
char *current_key = NULL;
cJSON_ArrayForEach(current_element, json)
{
current_key = current_element->string;
if (current_key != NULL)
{
(void) jrb_insert_str(b, strdup(current_element->valuestring), new_jval_v(current_key));
}
}
while(get_line(is_input) >= 0) {
for (i = 0; i < is_input->NF; i++) {
str = is_input->fields[i];
tmp = jrb_find_str(b, "10001011"); // This works but when I use "str" here instead of "10001011", I get a segmentation fault.
// tmp = jrb_find_str(b, str);
fprintf(fp, "%s ", tmp->val.s);
}
}
}
jettison_inputstruct(is_input);
fclose(fp);
return;
}
The .key file is like this:
{
"hi": "0",
"merhaba": "10",
"hallo": "11"
}
After running the program with printf I get a Segmentation fault after printing it is data like this:
0 10 11Segmentation fault (core dumped)
But if I try to use fprintf to write it into another file I directly get the Segmentation fault error.
I tried to debug and I see that the tmp value is null but how can it be null?
About JRB: http://web.eecs.utk.edu/~jplank/plank/classes/cs360/360/notes/JRB/index.html
Input struct:
const char *name; /* File name */
FILE *f; /* File descriptor */
int line; /* Line number */
char text1[MAXLEN]; /* The line */
char text2[MAXLEN]; /* Working -- contains fields */
int NF; /* Number of fields */
char *fields[MAXFIELDS]; /* Pointers to fields */
int file; /* 1 for file, 0 for popen */
I have read a lot documentation about this subject but i still have some problem about this,ı know what pointer is but when i try to use ı am facing some problem ,at below code,txt file includes just one words at every line.I tried the read random line from text and return to main function cause after i will need this).And i print it in main function ,please can you help me which section should i change in this code?(When ı try to run this the error message is Segmentation fault (core dumped))
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char word(char *file, char str[], int i);
int main() {
char buf[512];
char j = word("words.txt", buf, 512);
puts(j); // print random num
}
char word(char *file, char str[], int i) {
int end, loop, line;
FILE *fd = fopen(file, "r");
if (fd == NULL) {
printf("Failed to open file\n");
return -1;
}
srand(time(NULL));
line = rand() % 100 + 1; // take random num
for (end = loop = 0; loop < line; ++loop) {
if (0 == fgets(str, sizeof(str), fd)) { // assign text within a random line to STR
end = 1;
break;
}
}
if (!end)
return (char*)str; // return the str pointer
fclose(fd);
}
You reopened the file, this might be the case. You don't close the file if it returns in if(!end) part the fd is not closed.
And the function takes char but actually needs char *
char word(char *file, char str, int i);
int main() {
char * buf = malloc(sizeof(char)*512);
char *words = "words.txt";
char* j = word(words, buf, 512);
puts(j); // print random num
}
char word(char *file, char str[], int i) { // FIX HERE
int end, loop, line;
FILE *fd = fopen(file, "r"); //
if (fd == NULL) {
printf("Failed to open file\n");
return -1;
}
srand(time(NULL));
line = rand() % 100 + 1; // take random num
for (end = loop = 0; loop < line; ++loop) {
if (0 == fgets(str, sizeof(str), fd)) { // MAIN PROBLEM, PUT A CHAR* TO STR.
end = 1;
break;
}
}
fclose(fd); // YOU DIDN'T CLOSE IF IT RETURNED BEFORE
if (!end)
return str; // return the str pointer
//NOTHING IS RETURNED HERE
return str;
// I guess the problem is here, you return nothing and the function finishes, and you try to write that nothing with puts function which may cause a seg fault.
}```
I wrote the next function that tries to read and enter each line from text file into a string array in c :
int main(int argc,char* argv[])
{
char ** lines;
readFile(argv[1],lines);
}
int readFile(char* filePath,char** lines)
{
char file_char;
int letter_in_line=0;
int line=1;
char* line_string=malloc(1024);
int j=1;
int fd=open(filePath,O_RDONLY);
if (fd < 0)
{
return 0;
}
while (read(fd,&file_char,1) >0)
{
if(file_char != '\n' && file_char != '0x0')
{
line_string[letter_in_line] = file_char;
letter_in_line++;
}
else
{
if(lines != NULL)
{
lines=(char**)realloc(lines,sizeof(char*)*line);
}
else
{
lines=(char**)malloc(sizeof(char*));
}
char* line_s_copy=strdup(line_string);
lines[line-1]=line_s_copy;
line++;
letter_in_line=0;
memset(line_string,0,strlen(line_string));
}
j++;
}
printf("cell 0 : %s",lines[0]);
return 1;
}
I have 2 questions :
1)Whenever the code reaches the print of cell 0, I'm getting
Segmentation fault (core dumped) error. What is wrong ?
2)In case I
want to see the changes in the lines array in my main, I should pass
&lines to the func and get char*** lines as an argument ? In
addition, I will need to replace every 'line' keyword with '*line' ?
*I know that I can use fopen,fget, etc... I decided to implement it in this way for a reason.
There is many issues that make your code core dump.
Here a version very similar to your code. I hope it will help you to understand this.
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
int read_file(const char *filename, char ***result)
{
/* open the file */
const int fd = open(filename, O_RDONLY);
if (fd < 0) {
*result = NULL;
return -1;
}
/* read the file characters by characters */
char *buffer = (char *)malloc(sizeof(char) * 1024);
char c;
int column = 0;
int line = 0;
*result = NULL;
/* for each characters in the file */
while (read(fd, &c, 1) > 0) {
/* check for end of line */
if (c != '\n' && c != 0 && column < 1024 - 1)
buffer[column++] = c;
else {
/* string are null terminated in C */
buffer[column] = 0;
column = 0;
/* alloc memory for this line in result */
*result = (char **)realloc(*result, sizeof(char *) *
(line + 1));
/* duplicate buffer and store it in result */
(*result)[line++] = strdup(buffer);
}
}
free(buffer);
return line;
}
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "usage: %s [filename]", argv[0]);
return 1;
}
char **lines;
int line_count = read_file(argv[1], &lines);
if (line_count < 0) {
fprintf(stderr, "cannot open file %s\n", argv[1]);
return 1;
}
for(int i=0; i < line_count; i++)
printf("%s\n", lines[i]);
return 0;
}
Here an other version:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int read_file(const char *filename, char ***result)
{
/* init result */
*result = NULL;
/* open the file */
FILE *file = fopen(filename, "r");
if (file == NULL)
return -1;
/* read the file line by line */
char *buffer = (char *)malloc(sizeof(char) * 1024);
int line = 0;
while (fgets(buffer, 1024, file)) {
*result = (char **)realloc(*result, sizeof(char *) *
(line + 1));
(*result)[line++] = strdup(buffer);
}
free(buffer);
return line;
}
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "usage: %s [filename]", argv[0]);
return 1;
}
char **lines;
int line_count = read_file(argv[1], &lines);
if (line_count < 0) {
fprintf(stderr, "cannot open file %s\n", argv[1]);
return 1;
}
for(int i=0; i < line_count; i++)
printf("%s\n", lines[i]);
return 0;
}
Im new to c and am trying to understand pointers.
here I am opening a file and reading the lines given. Im trying to append these lines into an array and return it from the function. I dont seem to be appending or accessing the array correctly. output[count] = status; gives an error with mismatched char and char *.
Im essentially trying to get an array with a list of words given by a file where each element in the array is a word.
char *fileRead(char *command, char output[255]) {
int count = 0;
char input[255];
char *status;
FILE *file = fopen(command, "r");
if (file == NULL) {
printf("Cannot open file\n");
} else {
do {
status = fgets(input, sizeof(input), file);
if (status != NULL) {
printf("%s", status);
strtok(status, "\n");
// add values into output array
output[count] = status;
++count;
}
} while (status);
}
fclose(file);
return output;
}
I access fileRead via:
...
char commandArray[255];
char output[255];
int y = 0;
char *filename = "scriptin.txt";
strcpy(commandArray, fileRead(filename, output));
// read from array and pass into flag function
while (commandArray[y] != NULL) {
n = flagsfunction(flags, commandArray[y], sizeof(buf), flags.position, &desc, &parentrd, right, left, lconn);
y++;
...
Example of Read from file Line by line then storing nonblank lines into an array (array of pointer to char (as char*))
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//for it does not exist because strdup is not a standard function.
char *strdup(const char *str){
char *ret = malloc(strlen(str)+1);
if(ret)
strcpy(ret, str);
return ret;
}
//Read rows up to 255 rows
int fileRead(const char *filename, char *output[255]) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("Cannot open file:");
return 0;
}
int count = 0;
char input[255];
while(count < 255 && fgets(input, sizeof(input), file)) {
char *line = strtok(input, "\n");
if(line)//When it is not a blank line
output[count++] = strdup(line);//Store replica
}
fclose(file);
return count;
}
int main(void){
char *output[255];//(`char *` x 255)
int number_of_read_line = fileRead("data.txt", output);
for(int i = 0; i < number_of_read_line; ++i){
printf("%s\n", output[i]);
free(output[i]);//Discard after being used
}
return 0;
}
I have a struct of strings with 3 million lines. I am trying to sort the file like:
aaaaa
aaaab
aaacc
And so on.
I was trying to do bubblesort. I tried it with 10 lines and it worked, but when I tried the whole 3 million lines file it took over 30 minutes and was still processing. I decided to try quicksort. However, I am running into a problem where it says:
expected 'const char **' but argument is of type 'struct lines *'
How can I fix this? Here is what I am doing:
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
#include <ctype.h>
void swap_str_ptrs(char const **arg1, char const **arg2)
{
const char *tmp = *arg1;
*arg1 = *arg2;
*arg2 = tmp;
}
void quicksort_strs(char const *args[], unsigned int len)
{
unsigned int i, pvt=0;
if (len <= 1)
return;
// swap a randomly selected value to the last node
swap_str_ptrs(args+((unsigned int)rand() % len), args+len-1);
// reset the pivot index to zero, then scan
for (i=0;i<len-1;++i)
{
if (strcmp(args[i], args[len-1]) < 0)
swap_str_ptrs(args+i, args+pvt++);
}
// move the pivot value into its place
swap_str_ptrs(args+pvt, args+len-1);
// and invoke on the subsequences. does NOT include the pivot-slot
quicksort_strs(args, pvt++);
quicksort_strs(args+pvt, len - pvt);
}
void main()
{
FILE *dnaFile=fopen("hs_alt_HuRef_chr2.fa", "r"); //file im reading
typedef struct lines
{
char lines[100]; //size of each line
} lines;
int i = 0;
char buf[256];
static lines myDNA[3354419]; //creates the 3m spots for all lines
while (fgets (buf, sizeof(buf), dnaFile))
{
if (i > 0)
strcpy(myDNA[i].lines, buf); //inserting each line into the struct array
i++;
}
// this is the bubblesort approach, works, but it takes too lon
/**int a;
int total;
char temp[150];
char report[100][150];
for(a=0; a<3354419; a++)
{
for(total=a+1; total<=3354419; total++)
{
if(strcmp(myDNA[a].lines,myDNA[total].lines)>0)
{
strcpy(temp,myDNA[a].lines);
strcpy(myDNA[a].lines,myDNA[total].lines);
strcpy(myDNA[total].lines,temp);
}
}
}*/
quicksort_strs(myDNA, 3354419); //attempt at quicksort, which crashes
}
USING QSORT
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
#include <ctype.h>
int compare_function(const void *a,const void *b) {
return (strcmp((char *)a,(char *)b));
}
void main()
{
FILE *dnaFile=fopen("hs_alt_HuRef_chr2.fa", "r"); //file with 3 million lines
typedef struct lines
{
char lines[100];
} lines;
int i = 0;
char buf[256];
static lines myDNA[3354419]; // array holding the 3 million lines
while (fgets (buf, sizeof(buf), dnaFile))
{
if (i > 0)
strcpy(myDNA[i].lines, buf); //putting each line into array
i++;
}
qsort(myDNA, 1000, 100, compare_function); //qsort works for first 1k lines, after, messed up
int a;
for (a = 0; a < 1000; a++){
printf("%s", myDNA[a].lines); //printing lines
}
}
I have modified the question code a bit. From my testing, the following code appears to function as needed (as stated by the question).
#include <stdio.h> // printf(), fprintf(), fclose(), feof(), fgets(), fopen()
#include <string.h> // memset(), strcmp(), strdup()
#include <stdlib.h> // malloc(), qsort(), free()
#include <errno.h> // errno, ENOMEM, EIO
#define MAX_FILE_LINES 3354419
#define MAX_LINE_SIZE (255+1)
int compare_function(const void *a, const void *b)
{
return(strcmp(*(const char **)a, *(const char **)b));
}
int main(int argC, char *argV[])
{
int rCode = 0;
char *filePath = "hs_alt_HuRef_chr2.fa";
FILE *dnaFile = NULL;
char **myDNA = NULL;
int myDNAcnt = 0;
int index;
/** Allow user to specify the file path on the command-line. **/
if(argC > 1)
filePath=argV[1];
/** Allocate an array (to hold the 3 million lines). **/
errno=0;
myDNA=malloc(MAX_FILE_LINES * sizeof(*myDNA));
if(NULL == myDNA)
{
rCode=errno?errno:ENOMEM;
fprintf(stderr, "malloc() failed. errno:%d\n", errno);
goto CLEANUP;
}
memset(myDNA, 0, MAX_FILE_LINES * sizeof(*myDNA));
/** Open the file. **/
errno=0;
dnaFile=fopen(filePath, "r");
if(NULL == dnaFile)
{
rCode=errno;
fprintf(stderr, "fopen() failed to open \"%s\". errno:%d\n", filePath, errno);
goto CLEANUP;
}
/** Read the file into the array, allocating dynamic memory for each line. **/
for(myDNAcnt=0; myDNAcnt < MAX_FILE_LINES; ++myDNAcnt)
{
char buf[MAX_LINE_SIZE];
char *cp;
if(NULL == fgets(buf, sizeof(buf), dnaFile))
{
if(feof(dnaFile))
break;
rCode=EIO;
fprintf(stderr, "fgets() failed.\n");
goto CLEANUP;
}
cp=strchr(buf, '\n');
if(cp)
*cp='\0';
errno=0;
myDNA[myDNAcnt] = strdup(buf);
if(NULL == myDNA[myDNAcnt])
{
rCode=errno;
fprintf(stderr, "strdup() failed. errno:%d\n", errno);
goto CLEANUP;
}
}
/** Sort the array. **/
qsort(myDNA, myDNAcnt, sizeof(*myDNA), compare_function);
/** Print the resulting sorted array. **/
for(index=0; index < myDNAcnt; index++)
{
printf("%8d: %s\n",index, myDNA[index]); //printing lines
}
CLEANUP:
/** Close the file. **/
if(dnaFile)
fclose(dnaFile);
/** Free the array. **/
if(myDNA)
{
for(index=0; index < myDNAcnt; index++)
{
free(myDNA[index]);
}
free(myDNA);
}
return(rCode);
}