I am very new to C and I am having trouble with the most fundamental ideas in C. We are starting structures and basically the assignment we are working on is to read a delimited file and save the contents into a structure. The first line of the file has the number of entries and alls that I am trying to do at the moment is get the program to read and save that number and print it out. Please do not assume I know anything about C I really am very new to this.
This code is giving me a segmentation fault
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct info{
char name[100];
char number[12];
char address[100];
char city[20];
char state[2];
int zip;
};
int strucCount;
char fileText[1];
int main(char *file)
{
FILE *fileStream = fopen(file, "r");
fgets(fileText, 1, fileStream);
printf("\n%s\n",fileText);
fclose(fileStream);
}
Here is the sample file
4
mike|203-376-5555|7 Melba Ave|Milford|CT|06461
jake|203-555-5555|8 Melba Ave|Hartford|CT|65484
snake|203-555-5555|9 Melba Ave|Stamford|CT|06465
liquid|203-777-5555|2 Melba Ave|Barftown|CT|32154
Thanks for everyones comments, they helped a lot, sorry to Jim. I am working on very little sleep and didn't mean to offend anyone, I am sure we have all been there haha.
SUGGESTION:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLINE 80
#define MAXRECORDS 10
struct info{
char name[100];
char number[12];
char address[100];
char city[20];
char state[2];
int zip;
};
int
main(int argc, char *argv[])
{
FILE *fp = NULL;
int nrecs = 0;
char line[MAXLINE];
struct info input_records[MAXRECORDS];
/* Check for cmd arguments */
if (argc != 2) {
printf ("ERROR: you must specify file name!\n");
return 1;
/* Open file */
fp = fopen(argv[1], "r");
if (!fp) {
perror ("File open error!\n");
return 1;
}
/* Read file and parse text into your data records */
while (!feof (fp)) {
if (fgets(line, sizeof (line), fp) {
printf("next line= %s\n", line);
parse(line, input_records[nrecs]);
nrecs++;
}
}
/* Done */
fclose (fp);
return 0;
}
fclose(fileStream);
}
Key points:
Note use of "argc/argv[]" to read input filename from command line
line, nrecs, etc are all local variables (not globals)
Check for error conditions like "filename not given" or "unable to open file"
Read your data in a loop, until end of input file
Parse the data you've read from the text file into an array of binary records (TBD)
Related
I am trying to open the file indicated by the input file[100]. I keep getting a segmentation fault. I know that there is some problem with the fgets() function, but I am not exactly sure what it is. I can't get any code inside the loop to run. The final code is supposed to take the file from the first line of a text file, but it does not work. Any help would be appreciated, and I can post the main function code if needed!
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <numInt.h>
#include <string.h>
char *getCoeff(char file[100], char chemName[50])
{
FILE* fptr = fopen(file, "r");
char data[80];
char *dataptr = data;
char line[80];
int count = 0;
int i = 0;
printf("%s",file);
while (fgets(line, sizeof line, fptr) != NULL)
{
printf("Inside loop\n");
printf("%s",line);
strcpy(data,line);
}
fclose(fptr);
return dataptr;
}
#define LINES 4
#define LENGHT 30
typedef struct
{
char *name;
char *phoneNumber;
char *location;
char *traveltype;
} Client;
int main(int argc, char *argv[])
{
char *filename = argv[1];
char clientData[LINES][LENGHT];
readClientData(filename, clientData);
/* How to do this client struct */
Client *client = createClient(clientData[0], clientData[1], clientData[2], clientData[3]);
return 0;
}
void readClientData(char *filename, char clientData[LINES][LENGHT])
{
FILE *file = fopen(filename, "r");
if (file == NULL)
{
perror("Error while opening file!");
exit(1);
}
char line[LENGHT];
int i = 0;
while (fgets(line, LENGHT, file) != NULL)
clientData[i] = line; /* How to do this */
i++;
fclose(file);
}
Coming from a pythonista world I'm a bit confused how things are working here. It is clear that I can't just add lines to the list, nor can acces the lines the way I do to initialize the client struct.
Maybe I should just use a char *clientData[], but don't know how.
To copy C strings, you need to use:
char * strcpy ( char * destination, const char * source );
from the Standard C String Library, string.h.
However, notice, than unlike Python (your background), indentation does not define the body of the loop, you need to use curly brackets!
So, you need to do this:
while (fgets(line, LENGHT, file) != NULL)
{
strcpy(clientData[i], line);
i++;
}
Without the curly brackets, only the first immediate line of code will be considered to be the body of the loop. So, in the example above, the body of the loop - if we did not use curly brackets - would be only the call to the method for copying strings, and the increment of the counter would not be part of the loop!
You need to define, or just declare a method before using it, which you didn't do in your example.
Since you only need one client, you do not need a pointer, you can simply create one, by doing Client client;.
In order to keep it simple, use the knowledge you gathered from reading this answer so far, and do define the maximum length of the strings (that is the size of the arrays of characters every field of your struct gets to have). Remember, that C strings have to be NULL terminated, so, the maximum length of them is actually LENGTH - 1.
If you keep the fields of the struct as pointers to char, then you'd need to dynamically allocate memory, or set the pointer point to corresponding string of the clientData array (similarly to what you did for the file name). I suggest you get some experience in C first, and then try implementing these two approaches.
Now, you are ready to do:
strcpy(client.name, clientData[0]);
...
strcpy(client.traveltype, clientData[3]);
Complete working example:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LINES 4
#define LENGTH 30
typedef struct
{
char name[LENGTH];
char phoneNumber[LENGTH];
char location[LENGTH];
char traveltype[LENGTH];
} Client;
void readClientData(char *filename, char clientData[LINES][LENGTH]);
void printClient(Client client);
int main(int argc, char *argv[])
{
char *filename = NULL;
if(argc > 1)
filename = argv[1];
else
{
printf("Usage: %s <filename>\n", argv[0]);
}
char clientData[LINES][LENGTH];
readClientData(filename, clientData);
Client client;
strcpy(client.name, clientData[0]);
strcpy(client.phoneNumber, clientData[1]);
strcpy(client.location, clientData[2]);
strcpy(client.traveltype, clientData[3]);
printClient(client);
return 0;
}
void readClientData(char *filename, char clientData[LINES][LENGTH])
{
FILE *file = fopen(filename, "r");
if (file == NULL)
{
perror("Error while opening file!");
exit(1);
}
char line[LENGTH];
int i = 0;
while (fgets(line, LENGTH, file) != NULL)
{
line[strcspn(line, "\n")] = 0;
strcpy(clientData[i], line);
i++;
}
fclose(file);
}
void printClient(Client client)
{
printf("%s, %s, %s, %s\n", client.name, client.phoneNumber, client.location, client.traveltype);
}
Output:
Georgioss-MBP:Desktop gsamaras$ cat test.txt
MegasAlexandros
3335632320
Greece
Cosmos
Georgioss-MBP:Desktop gsamaras$ gcc main.c
Georgioss-MBP:Desktop gsamaras$ ./a.out test.txt
MegasAlexandros, 3335632320, Greece, Cosmos
PS: I used this in my example: Removing trailing newline character from fgets() input
I am new to programming. I want to take one commandline argument which is a filename and open that particular file and copy the contents to another file. I don't know how to convert the commandline argument to a string or file pointer. I checked strcpy and std::string which I found online but it didn't work. Please help me. I have pasted my code below
#include<string.h>
#include <stdio.h>
#include <stdlib.h>
void main(int argc, char *argv[])
{
char *inp;
strcpy(inp,argv[1]);
FILE *fp;
char str[5];
//printf("Enter the file name:");
//scanf("%s",fname);
if ((fp= fopen(inp, "r")) == NULL) {
printf("cannot open file");
exit(1);
}
FILE *fp1;
fp1=fopen("out.txt","w+");
while(!feof(fp)) {
fgets(str,4,fp);
printf("%s",str);
fprintf(fp1,"%s",str);
}
fclose(fp);
fclose(fp1);
}
Why not char *inp = argv[1];?
Or better yet:
fp = fopen(argv[1], "r");
The problem with your code is this:
char *inp;
strcpy(inp,argv[1]);
You're copying argv[1] into inp, but you have no idea what inp points to. If you really want to go that route, you have to allocate memory for inp.
char *inp = malloc(strlen(argv[1]) + 1); /* allocate enough for the string and null-terminator */
strcpy(inp,argv[1]); /* copy the contents */
Just remember to free() afterwards.
P.S. Never use while(!feof(fp)). Just use while(fgets(str,4,fp)).
See this question for more info.
I am new to C and I need to read in a .txt file where there are 3 fields in each line separated by a comma, and I need to save it into an array. I am wondering how to do this?
Here is an example file:
0, "test", 100
1, "hi", 2
2, "goodbye", 0
So I am wondering how to read the file line by line and to store each element into an array. I have started by defining a struct:
typedef struct data {
int col1;
char *col2;
int col3;
} data_t;
Could anyone help me out to get started with the file opening?
The SQLite shell has an .import command that reads CSV. It is worthy of study. You can find it here; search for CSVReader to see how it's coded.
For file opening there is a standard library (include stdio.h) function named fopen. It has the following declaration:
FILE *fopen(const char *filename, const char *mode);
As you can see it expects you to provide a pointer to const char for both filename and mode (read/write/read+write). It will return a pointer to a FILE so inside the function where you intend to work with it you'd have to declare one like this:
FILE *my_file;
It's also a good idea to initialize it to NULL so that you can check for errors when using fopen.
In your main function (purely for reading):
FILE *my_file = NULL;
my_file = fopen("filename.txt", "r");
And check for the returned pointer:
if (my_file == NULL)
//error message etc.
simply sample(check omit)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUMOFDATA 10
typedef struct data {
int col1;
char *col2;
int col3;
} data_t;
int main(){
data_t data_array[NUMOFDATA];
int data_count = 0;
char line[128];
FILE *fp;
fp=fopen("data.txt", "r");
while(fgets(line, sizeof(line), fp)){
int col1, col3;
char col2[64];
if(sscanf(line, "%d, %63[^,], %d", &col1, col2, &col3)==3){
char *cl2p = col2;
data_array[data_count].col1 = col1;
data_array[data_count].col3 = col3;
if(col2[0] == '"'){
char *p = strchr(&col2[1], '"');
if(p)
*p = '\0';
cl2p = &col2[1];
}
data_array[data_count].col2 = strdup(cl2p);
//printf("%d, \"%s\", %d\n",data_array[data_count].col1,data_array[data_count].col2,data_array[data_count].col3);
if(++data_count == NUMOFDATA)break;
}
}
fclose(fp);
return 0;
}
Hi I'm trying to read data from file into array of structures I tried to use fgets but got the error saying that RECORD type cannot be convert to char* this is what i have so far
#include <stdio.h>
#include <stdlib.h>
#define MAX_NAME 20
#define FILE_NAME 50
#define LIST_SIZE 50
//void getData(RECORD name[], RECORD score)
typedef struct RECORD
{
char *name;
float score;
}RECORD;
int main (void)
{
// Declarations
FILE *fp;
char fileName[FILE_NAME];
RECORD list[LIST_SIZE];
int count = 0;
// Statements
printf("Enter the file name: ");
gets(fileName);
fp = fopen(fileName, "r");
if(fp == NULL)
printf("Error cannot open the file!\n");
while (fgets(list[count], LIST_SIZE, fp) != NULL)
{
count++;
}
return 0;
}
the error occurs in the fgets statement inside while loop, how can i fix this and read data into array of structures?
thank in advance
fgets is used to input a string from a text file one line as a unit.
e.g.)
char input_line_buff[128];
fgets(input_line_buff, 128, fp);
read-in
input_line_buff:(contents eg) "name 66.6\n"
you do split , memory alloc and copy, and convert .
e.g.)
list[count].name = strdup("name");
list[count].score= atof("66.6");
count++;
Try this,
while(fgets((char *)list[count], SIZE/* data size to be read */, fp) != NULL)
{...}