how to read value in structure - c

I'm reading file using fread().[read file only]
On compilation, the compiler throws a "Segmentation fault (core dumped)" error.
I'm using structure.
I wrote this code.
type #include <string.h>
#include <stdio.h>
#include <stdlib.h>
int twilio_send_functionapi(char *channel, char *status); // function declartion
struct credentials
{
char *account_sid;
char *auth_token;
char *from_number;
char *to_number;
} c1;
int main(int argc, char *argv[])
{
FILE *fp;
struct credentials input;
fp = fopen("data.config", "r");
if (fp == NULL)
{
printf("Error\n");
return -1;
}
dentials.to_number = (char*)malloc(sizeof(char)*100);
while(fread(&c1,sizeof(struct credentials),1 ,fp))
fscanf(fp,"%s %s %s %s", c1.account_sid, c1.auth_token,c1.from_number, c1.to_number);
char *channel,*status;
channel = argv[1];
status = argv[2];
twilio_send_functionapi(channel,status); //function call
}
Don't know where I'm mistaken.
here is .conf file which needs to be read
account_sid : AC40cfb4f3e98b55b13a9b93527683171e
auth_token : 5f6906d7847ad1fc1fc1170ab60e40fd
from_number : 15867854760
to_number : 1212321123

Instead of fread(), fscanf(), use fgets() to read a line of the file into a string.
// 123456789 123456789 123456789 123456789
//account_sid : AC40cfb4f3e98b55b13a9b93527683171e
#define SID_LEN 34
struct credentials {
char account_sid[SID_LEN + 1]; // Use array here, not pointer.
// ... omitted for brevity
} c1;
#define LINE_SIZE 100
char line[LINE_SIZE];
if (fgets(line, sizeof line, fp)) {
if (sscanf(line, "account_sid : %34s", c1.account_sid) == 1) {
; // Success
} else {
; // Failed
}
Continue likewise for the other c1 members`.

Thank you everyone.
I resolve my problem.
char credential[4][100] ;
int main()
{
FILE *fp;
fp = fopen("data.config", "r");
if (fp == NULL)
{
printf("Error\n");
return -1;
}
printf("File is opened\n");
if ((fscanf(fp,"account_sid-%s\n",credential[0])!= 1))
{
printf("error reading account_sid value\n");
return -1;
}
fclose(fp);
}

Related

Either the condition fp==NULL is redundant or there is a possible null pointer dereference

I get the above error in CppCheck but I can't see what's wrong.I guess the error is the reason my code doesn't find any files,even if they exist in my computer.Any help is appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 80
char *getchoice(void);
void getfile(char *filename);
int main() {
char *choice;
choice=getchoice();
getfile(choice);
return 0;
}
char *getchoice(void) {
char *filename;
filename=malloc(SIZE);
printf("Enter the name of the text file: ");
scanf("%30s",filename);
return filename;
}
void getfile(char *filename) {
FILE *fp;
fp=fopen(filename,"r");
if (fp==NULL){
printf("The entered file does not exist.");
printf("\n");
}
else{
printf("The file exists.");
}
fclose(fp);
return;
}
Here is a list of things to do, in order to clean up this program:
Handle the event that malloc fails, so that scanf and getfile are not passed NULL.
Check that scanf successfully performed the expected number of conversions, to ensure filename contains valid data.
Use perror to give more accurate information about why malloc or fopen failed.
Avoid passing NULL to fclose, in the event that fopen failed.
free memory allocated by malloc (Unlike fclose, free may be safely passed NULL).
#include <stdio.h>
#include <stdlib.h>
char *getchoice(void);
void getfile(char *filename);
int main(void) {
char *choice = getchoice();
if (choice)
getfile(choice);
free(choice);
}
char *getchoice(void) {
char *filename = malloc(80);
if (filename) {
printf("Enter the name of the text file: ");
if (1 != scanf("%79s", filename)) {
free(filename);
return NULL;
}
} else {
perror("malloc");
}
return filename;
}
void getfile(char *filename) {
FILE *fp = fopen(filename, "r");
if (fp) {
puts("File opened.");
fclose(fp);
} else {
perror("fopen");
}
}

Reading data from file into structure in c programming language

I want to read data from txt file and save those data in variables not just print output. How do I save those data from text file in variables?
I tried like this and it did not work out:
int value1 ;
object2->value =&value1 ;
*(object2->value) = value1 ;
My txt file looks like this:
INT
A
5
and my code looks like this:
#include <stdio.h>
#include <stdlib.h> // For exit()
struct variable {
char type[10];
char name[10];
int value;
};
int main(){
struct variable *object2=malloc(sizeof(struct variable));
FILE * file= fopen("input.txt", "rb");
if (file != NULL) {
fread(object2, sizeof(struct variable), 1, file);
fclose(file);
}
int value1 ;
object2->value =&value1 ;
*(object2->value) = value1 ;
printf("%d\n",value1);
printf("%s/%s/%d\n",object2->type,object2->name,object2->value);
}
File format:
CHAR
B
6
INT
A
5
FLOAT
C
7
This is my solution:
#include <stdio.h>
#include <stdlib.h> // For exit()
#include <string.h>
#define BUFF_SIZE 1024
#define NAME_TYPE_SIZE 10
#define VALUE_SIZE 20
#define NOT_ENOUGH_MEMORY 1
#define CANT_OPEN_FILE 2
#define FILE_ENDED 3
#define TOO_BIG_STR 4
#define CANT_FORMAT_VALUE 5
#define NOT_FOUND_LINE 6
#define SEARCH_NAME "A"
#pragma warning(disable : 4996) // for vs
struct variable {
char type[NAME_TYPE_SIZE];
char name[NAME_TYPE_SIZE];
int value;
};
int find_var_in_file(char* file_path, char* find_name, struct variable* dest);
int main()
{
struct variable* object2 = malloc(sizeof(struct variable));
if (NULL == object2)
{
printf("not enough memory");
return NOT_ENOUGH_MEMORY;
}
int error = find_var_in_file("input.txt", SEARCH_NAME, object2);
if (CANT_OPEN_FILE == error)
{
return printf("can't open file");
}
if (error == 0)
{
// Printing data to check validity
printf("read: type: %s name: %s value: %d", object2->type, object2->name, object2->value);
int a = object2->value;
// do stuff with a
}
else
{
if (error == NOT_FOUND_LINE)
{
printf("not find the var \"" SEARCH_NAME "\" in the file");
}
else
{
printf("error reading the file. error code: %d", error);
}
}
free(object2);
return 0;
}
int read_line(char* buffer, int buffer_size, char* dest, int dest_size, FILE* stream)
{
if (!fgets(buffer, buffer_size, stream))
{
return NOT_FOUND_LINE;
}
int read_len = strlen(buffer);
if ('\n' == buffer[read_len - 1])
{
if (read_len == 1)
{
return NOT_FOUND_LINE;
}
buffer[read_len - 1] = '\0'; // remove "\n" in the end
}
if (dest_size <= strlen(buffer)) // last chat is null
{
return TOO_BIG_STR;
}
strcpy(dest, buffer);
// clear the read
memset(buffer, '\0', read_len);
return 0;
}
int find_var_in_file(char* file_path, char* find_name, struct variable* dest)
{
char file_buffer[BUFF_SIZE] = { 0 }; // Buffer to store data
FILE* stream = fopen(file_path, "r");
if (NULL == stream)
{
return CANT_OPEN_FILE;
}
int error = 0;
while (1)
{
// read type
int read_type_result = read_line(file_buffer, BUFF_SIZE, dest->type, NAME_TYPE_SIZE, stream);
if (read_type_result != 0)
{
error = read_type_result;
break;
}
int read_name_result = read_line(file_buffer, BUFF_SIZE, dest->name, NAME_TYPE_SIZE, stream);
if (read_name_result != 0)
{
error = read_name_result;
break;
}
char value_buffer[VALUE_SIZE] = { 0 };
int read_value_result = read_line(file_buffer, BUFF_SIZE, value_buffer, VALUE_SIZE, stream);
if (read_value_result != 0)
{
error = read_value_result;
break;
}
if (0 == strcmp(find_name, dest->name))
{
if (1 != sscanf(value_buffer, "%d", &dest->value))
{
error = CANT_FORMAT_VALUE;
}
break;
}
}
fclose(stream);
return error;
}
You just need to call the function find_var_in_file like in main. I loop over all the lines of the file and search for the var name. If have formating error or not find the name of the var in the file return the error code.
If the file you are trying to read is a text file (which it is in your case), then use fgets() to read its content. Also, if its content has a consistent format, then consider using sscanf() to do your parsing.
I don't understand why you are using a pointer to struct variable to save data. You can simply use a struct variable object and access its fields with .
Your code should look something like that:
#include <stdio.h>
#include <stdlib.h> // For exit()
#include <string.h> // for strlen()
struct variable {
char type[10];
char name[10];
int value;
};
int main()
{
FILE *file = fopen("input.txt", "r");
if (!file) {
fprintf(stderr, "Could not read file\n");
return 1;
}
struct variable object2;
char buffer[1024];
while (fgets(buffer, 1024, file)) {
if (sscanf(buffer, "%9s %9s %d", object2.type, object2.name, &object2.value) != 3) {
fprintf(stderr, "Error parsing file\n");
fclose(file);
return 1;
}
printf("%s %s %d\n", object2.type, object2.name, object2.value);
}
fclose(file);
}
Now, if you want to store all the lines of your file into variables to use them later, then first you need to count the number of lines in your file (let's call it n) and second, allocate a dynamic array of size n.
fscanf(file,"%s\n%s\n%d\n",object2->type,object2->name,&object2->value);

How to store the contents of a file into an array (until its maximum capacity)

In my file functions.c I have been trying to store the contents of a *.txt file into an array. It does work. However, it should only store it to its size. For example, if the array is size 5, it can only store 5 records and ignore the rest.
file.txt:
34
firstname
46
secondname
78
thirdname
avatar.h:
struct avatar
{
int score;
char name[25];
};
functions.h:
#include "avatar.h"
int readfile( struct avatar [], int*, char [ ] )
functions.c:
#include <stdio.h>
#include "functions.h"
int readfile(struct pokemon avatararray[], int * i, char filename[]) {
FILE * fp;
struct avatar rd;
fp = fopen(filename, "r");
if (fp == NULL) {
return -1;
}
while (fscanf(fp, "%d ", & rd.score) != EOF) {
avatararray[ * i] = read;
* i += 1;
}
}
return *i;
}
main.c:
#include <stdio.h>
#include "functions.h"
int main(int argc, char * argv[]) {
struct avatar avatarbank[5];
int numavatars;
char filename[] = "somefile.txt";
readfile(avatarbank, &numavatars, filename)
}
You probably want something like this:
// Read avatars froma file into an array
// avatararray : pointer to array
// arraysize : maximum size of array
// filename : filename to read from
// return value : number of avatars read, -1 if file could not be opened
//
int readfile(struct pokemon avatararray[], int arraysize, char filename[]) {
int itemsread = 0;
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
return -1;
} else {
struct avatar rd;
while (arraysize-- >= 0 && fscanf(fp, "%d %s", & rd.level, rd.name) != EOF) {
avatararray[itemsread++] = rd;
}
}
fclose(fp); // don't forget to close the file
return itemsread;
}
#define ARRAYSIZE 5
int main(int argc, char * argv[]) {
struct avatar avatarbank[ARRAYSIZE];
char filename[] = "file.txt";
int itemsread = readfile(avatarbank, ARRAYSIZE, filename);
if (itemsread != -1)
{
printf("Read %d items\n", itemsread);
}
else
{
printf("Could not read items\n");
}
}
Disclaimer: this is untested code that may not even compile, but you should get the idea.

C Program - warning: assignment makes pointer from integer without a cast

I'm trying to read a file and store its content in a variable, here's my code:
#define _BSD_SOURCE
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
// CEK ROUTER MODEL
char* router_model;
char* model() {
char filename[] = "/tmp/cpuinfo";
char* key = "system type";
char* value;
FILE *file = fopen(filename, "r");
if (file != NULL) {
char line[1000];
while (fgets(line, sizeof line, file) != NULL) /* read a line from a file */ {
//fprintf(stdout, "%s", line); //print the file contents on stdout.
if (strncmp(line, key, strlen(key)) == 0) {
char* value = strchr(line, ':');
value += 2;
router_model = strdup(value);
break; // once the key has been found we can stop reading
}
}
fclose(file);
}
else {
perror(filename); //print the error message on stderr.
}
return router_model;
}
// TULIS SERIAL NUMBER KE FILE
char tulis(char p[100]) {
// Write a serial number to a file
char sn[30];
char encrypt_sn[300];
printf("Serial Number:\n");
scanf("%s", sn);
FILE *f = fopen("/tmp/halo/fsn-55cfc8770b69cc07268fae7f25ee444c", "w");
if (f == NULL) {
printf("Error opening file!\n");
exit(1);
}
fprintf(f,"Serial Number: %s", sn);
fclose(f);
sprintf(encrypt_sn, "ccrypt -e /tmp/halo/fsn-55cfc8770b69cc07268fae7f25ee444c -K %s", p);
system(encrypt_sn);
system("mv /tmp/halo/fsn-55cfc8770b69cc07268fae7f25ee444c.cpt /tmp/halo/fsn-55cfc8770b69cc07268fae7f25ee444c");
printf("Serial number is saved in /tmp/halo/fsn-55cfc8770b69cc07268fae7f25ee444c\n");
return 0;
}
// BACA SERIAL NUMBER & SIMPAN DALAM SEBUAH VARIABLE
char baca(char p[100]) {
// Store the serial number from a file in a variable
char line[50];
char decrypt_sn[300];
char key[30] = "Serial Number";
char *serial_number;
if( access( "/tmp/halo/fsn-55cfc8770b69cc07268fae7f25ee444c", F_OK ) != -1 ) {
system("cp /tmp/halo/fsn-55cfc8770b69cc07268fae7f25ee444c /tmp/");
system("mv /tmp/fsn-55cfc8770b69cc07268fae7f25ee444c /tmp/fsn-55cfc8770b69cc07268fae7f25ee444c.cpt");
sprintf(decrypt_sn, "ccrypt -d /tmp/fsn-55cfc8770b69cc07268fae7f25ee444c.cpt -K %s", p);
system(decrypt_sn);
FILE *file = fopen("/tmp/fsn-55cfc8770b69cc07268fae7f25ee444c", "r");
if (file == NULL) {
printf("Error opening file!\n");
exit(1);
}
while (fgets(line, sizeof line, file) != NULL) /* read a line from a file */ {
//fprintf(stdout, "%s", line); //print the file contents on stdout.
if (strncmp(line, key, strlen(key)) == 0) {
char* value = strchr(line, ':');
value += 2;
serial_number = strdup(value);
break; // once the key has been found we can stop reading
}
}
fclose(file);
//printf("Your hardware serial number is: (%s)\n", serial_number);
remove("/tmp/fsn-55cfc8770b69cc07268fae7f25ee444c");
}
else {
printf("fsn not found\n");
return -1;
}
return 0;
}
int main(int argc, char* argv[]) {
char *r;
char *del;
char *decrypt;
int ret;
char input[30];
char *p;
char *original_sn;
p = "MmI4MTUxM2FjMjRlMDkzYmRkZGQyMjcwMjQ4OWY3MDAwNGZiYTM0MWNkZGIxNTdlYzAxN2";
//tulis(p);
original_sn = baca(p);
printf("SN: %s\n", original_sn);
return 0;
}
The file is /tmp/halo/fsn-55cfc8770b69cc07268fae7f25ee444c and the content of that file is Serial Number: 1866203214226041 and original_sn should output 1866203214226041. However when I run that code I get:
test.c: In function ‘main’:
test.c:105:14: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
original_sn = baca(p);
^
SN: (null)
How do I fix it ?
This happens because your baca function returns a char, whereas you are assigning its return value to a char *. Maybe you wanted to use a char variable.
If function baca can change the contents of the memory block pointed by the input argument:
Change this:
char* p = "MmI4MTUxM2FjMjRlMDkzYmRkZGQyMjcwMjQ4OWY3MDAwNGZiYTM0MWNkZGIxNTdlYzAxN2";
To this:
char p[] = "MmI4MTUxM2FjMjRlMDkzYmRkZGQyMjcwMjQ4OWY3MDAwNGZiYTM0MWNkZGIxNTdlYzAxN2";
If function baca cannot change the contents of the memory block pointed by the input argument:
Change this:
char baca(char p[])
To this:
char baca(const char* p)
In baca you are allocating initialised memory using strdup:
serial_number = strdup(value);
, then you do nothing with that.
It is clear that you think that the function returns a pointer to that memory so you can print it's content. However, it is not what you are doing. Because all your baca function is doing is returning a value indecating if it sucseede (0) or not (-1). And you are jut ignoring that pointer and leaving some wasted unused memory allocated by your prog.
Their are 2 methodes to fix your code:
Method1 : returning the serial_number
char* baca(const char* p) {
// Store the serial number from a file in a variable
char line[50];
char decrypt_sn[300];
char key[30] = "Serial Number";
char *serial_number=NULL;
if( access( "/tmp/halo/fsn-55cfc8770b69cc07268fae7f25ee444c", F_OK ) != -1 ) {
system("cp /tmp/halo/fsn-55cfc8770b69cc07268fae7f25ee444c /tmp/");
system("mv /tmp/fsn-55cfc8770b69cc07268fae7f25ee444c /tmp/fsn-55cfc8770b69cc07268fae7f25ee444c.cpt");
sprintf(decrypt_sn, "ccrypt -d /tmp/fsn-55cfc8770b69cc07268fae7f25ee444c.cpt -K %s", p);
system(decrypt_sn);
FILE *file = fopen("/tmp/fsn-55cfc8770b69cc07268fae7f25ee444c", "r");
if (file == NULL) {
printf("Error opening file!\n");
exit(1);
}
while (fgets(line, sizeof line, file) != NULL) /* read a line from a file */ {
//fprintf(stdout, "%s", line); //print the file contents on stdout.
if (strncmp(line, key, strlen(key)) == 0) {
char* value = strchr(line, ':');
if(value!=NULL){/*testing the return value for erros so you prog doesn't cruch*/
value += 2;
serial_number = strdup(value);
}
/*in case off erreor you can choose one of two options:*/
/*optinon1: print an error mesage then kill your prog*/
else{
printf("Error: corrupted file!\n");
exit(1);
}
/*option 2: removing the else part your baca then will return NULL and the calling code should understand that an error has occured*/
break;
}
}
fclose(file);
remove("/tmp/fsn-55cfc8770b69cc07268fae7f25ee444c");
}
else {
printf("fsn not found\n");
}
return serial_number;
}
int main(int argc, char* argv[]) {
char *r;
char *del;
char *decrypt;
int ret;
char input[30];
char *p;
char *original_sn;
p = "MmI4MTUxM2FjMjRlMDkzYmRkZGQyMjcwMjQ4OWY3MDAwNGZiYTM0MWNkZGIxNTdlYzAxN2";
//tulis(p);
original_sn = baca(p);
if(original_sn!=NULL){
printf("SN: %s\n", original_sn);
free(original_sn);/*you should free the memory allocated by strdup once you are done using it.*/
}
else{
printf("An error has occured\n");
}
return 0;
}
Method2 : pass by reference
char baca(const char* p, char **serial_number) {
// Store the serial number from a file in a variable
char line[50];
char decrypt_sn[300];
char key[30] = "Serial Number";
char ret = 0;/*the return value 0 means no error.*/
if( access( "/tmp/halo/fsn-55cfc8770b69cc07268fae7f25ee444c", F_OK ) != -1 ) {
system("cp /tmp/halo/fsn-55cfc8770b69cc07268fae7f25ee444c /tmp/");
system("mv /tmp/fsn-55cfc8770b69cc07268fae7f25ee444c /tmp/fsn-55cfc8770b69cc07268fae7f25ee444c.cpt");
sprintf(decrypt_sn, "ccrypt -d /tmp/fsn-55cfc8770b69cc07268fae7f25ee444c.cpt -K %s", p);
system(decrypt_sn);
FILE *file = fopen("/tmp/fsn-55cfc8770b69cc07268fae7f25ee444c", "r");
if (file == NULL) {
printf("Error opening file!\n");
exit(1);
}
while (fgets(line, sizeof line, file) != NULL) /* read a line from a file */ {
//fprintf(stdout, "%s", line); //print the file contents on stdout.
if (strncmp(line, key, strlen(key)) == 0) {
char* value = strchr(line, ':');
if(value!=NULL){/*testing the return value for erros so you prog doesn't cruch*/
value += 2;
*serial_number = strdup(value);
}
/*in case off erreor you can choose one of two options:*/
else{
/*optinon1: print an error mesage then kill your prog*/
/*option 2: making the return value non 0 and the calling code should understand that an error has occured*/
#define OPTION1
#ifdef OPTION1
printf("Error: corrupted file!\n");
exit(1);
#else
ret=-2; //to used this option comment out #define OPTION1
#endif
}
break;
}
}
fclose(file);
remove("/tmp/fsn-55cfc8770b69cc07268fae7f25ee444c");
}
else {
printf("fsn not found\n");
ret=-1;
}
return ret;
}
int main(int argc, char* argv[]) {
char *r;
char *del;
char *decrypt;
int ret;
char input[30];
char *p;
char *original_sn=NULL;
p = "MmI4MTUxM2FjMjRlMDkzYmRkZGQyMjcwMjQ4OWY3MDAwNGZiYTM0MWNkZGIxNTdlYzAxN2";
//tulis(p);
switch(baca(p,&original_sn))
{
case 0: //evrything is fine
printf("SN: %s\n", original_sn);
free(original_sn);
break;
case -1:/* handle each error as you should*/
case -2:
default:
printf("An error has occured\n");
}
return 0;
}
Hope this helps. :).

Reading 2 byte at a time from a binary file

I have an elf file that called example. I wrote following code which it's read the content of the example file in the binary mode and then I wanted to save their content in another file called example.binary. But when I run the following program it shows me a segmentation fault. What's wrong with this program? I can't find out my mistake.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// typedef macro
typedef char* __string;
//Function prototypes
void readFileToMachine(__string arg_path);
int main(int argc, char *argv[]) {
__string pathBinaryFile;
if(argc != 2){
printf("Usage : ./program file.\n");
exit(1);
}
pathBinaryFile = argv[1];
readFileToMachine(pathBinaryFile);
return EXIT_SUCCESS;
}
void readFileToMachine(__string arg_path){
int ch;
__string pathInputFile = arg_path;
__string pathOutputFile = strcat(pathInputFile, ".binary");
FILE *inputFile = fopen(pathInputFile, "rb");
FILE *outputFile = fopen(pathOutputFile, "wb");
ch = getc(inputFile);
while (ch != EOF){
fprintf(outputFile, "%x" , ch);
ch = getc(inputFile);
}
fclose(inputFile);
fclose(outputFile);
}
You have no room to concatenate extention to path so you have to create space for that.
One solution could be:
char ext[] = ".binary";
pathOutputFile = strdup(arg_path);
if (pathOutputFile != NULL)
{
pathOutputFile = realloc(pathOutputFile, strlen(arg_path) + sizeof(ext));
if (pathOutputFile != NULL)
{
pathOutputFile = strcat(pathInputFile, ext);
// YOUR STUFF
}
free(pathOutputFile);
}
Side note: typedef a pointer is not a good idea...
change your typedef to typedef char* __charptr
void rw_binaryfile(__charptr arg_path){
FILE *inputFile;
FILE *outputFile;
__charptr extension = ".binary";
__charptr pathOutputFile = strdup(arg_path);
if (pathOutputFile != NULL){
pathOutputFile = realloc(pathOutputFile, strlen(arg_path) + sizeof(extension));
if (pathOutputFile != NULL){
pathOutputFile = strcat(pathOutputFile, ".binary");
inputFile = fopen(arg_path, "rb");
outputFile = fopen(pathOutputFile, "wb");
write_file(inputFile, outputFile);
}
}
}
void write_file(FILE *read, FILE *write){
int ch;
ch = getc(read);
while (ch != EOF){
fprintf(write, "%x" , ch);
ch = getc(read);
}
}

Resources