How to read a file with mixture of data in C? - c

I am trying to read a file that is like
91242 FirstName1_LastName1 3.02
I try to use fscanf to read the file and I am confused how to read the second element that with a mixture of character and int. I'm just using one statement to read for test only. I will modify it to a while loop to read the whole text file.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "linked_list.h"
int main() {
node *list_head = NULL;
FILE *file;
file = fopen("student.txt", "r");
if (file == NULL) {
printf("Can not find the file.\n");
}
else {
printf("File students.txt opened successfully.\n");
printf("Linked list built from file students.txt successfully\n");
}
student s;
fscanf(file,"%d%s%lf", &s.id,s.name,&s.gpa);
insert_last(&list_head, s);
print_list(list_head);
}
Here is what i got when I print it out.
91242 FirstName1_LastName1)\�#�4� 3.02
Here is my student.c document
#include "student.h"
void print_student(student student_record){
printf("%d\t%s\t%.2f\n", student_record.id, student_record.name,
student_record.gpa);
}
And here is the definition of student.
 typedef struct{ int id; char name[20]; double gpa; } student;

Related

How can I write int value Binary and txt file in C?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
struct student
{
int stuNum;
int point;
};
int newStudent(FILE* dataf, FILE* indexf);
int main(void)
{
FILE* datafile;
FILE* indexfile;
indexfile = fopen("indexDosyasi.txt", "a+");
datafile = fopen("veriDosyasi.bin", "wb+");
newStudent(datafile, indexfile);
fclose(datafile);
fclose(indexfile);
return 0;
}
int newStudent(FILE* dataf, FILE* indexf)
{
indexf = fopen("indexfile.txt", "a+"); // txt file
dataf = fopen("datafile.bin", "wb"); // binary file
if (dataf == NULL)
{
printf("error");
return -1;
}
struct student* last = (struct student*)malloc(sizeof(struct student));
printf("number of student \n");
scanf("%d", last->stuNum);
fprintf(indexf, "%d\t", last->stuNum);
fwrite(last, sizeof(struct student), 1, dataf);
// fwrite(&last->stuNum,sizeof(struct student),1,dataf);
return 0;
}
Hi , i am trying student add system with c , my datafile have to be binary file and my indexfile have to be txt file , stuNum and point have to be int value but i cant add stunum and point into datafile and indexfile , i dont understand how can i add ? i read a lot answer about this question but i didnt find answer i want .When i run this code and enter the student number is 875,it says 66955608268424 in the indexfile(txt) and it says �*~ in the datafile(binary).i cant understand where is mistake?
Can you help me?
Try this way:
int newStudent(...)
{
write(fileName, "what you want to write", strlen("what you want to write"))
}
And if it doesn't works, try to tranform your int to a character string. I thing it is the itoa() or atoi() function.

how to print the content of a text file in c

Iam trying to print the content of a text file called text.txt in the terminal in c I have the following code but it doesn't work:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(){
char str[255];
FILE *fp;
fp = fopen("text.txt","r");
while (fgets(str,255,fp)!=NULL){
printf("%s",str);
fclose(fp);
};
}
I couldn't find a solution please help
First of all, you are closing the file inside the loop. fclose should lie at the end of your program. Secondly, fopen() might fail (you don't have permission to read the file for example). So, don't forget to handle that too.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(){
const int sz = 255;
char str[sz];
FILE *fp;
fp = fopen("input.txt","r");
if(fp == NULL){
// opening the file failed ... handle it
}
while (fgets(str,sz,fp)!=NULL){
printf("%s",str);
};
fclose(fp);
}
Here is another similar way
if (fp!=NULL)
{
// file open succeded. do sth with it.
fclose (fp);
}
Hope this helps and keep coding!

How can I open a file in c using fgets() and an input file?

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

How to copy the contents from the last line of a text file to the first line? C programming

I am writing a program to copy a text file "input.txt" to "output.txt" however instead of copying the first line to the last line I would need to inversely copy the last line to the first line to the "output.txt" file. Could someone please give some advice thanks!
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
char filename[]={"input.txt"};
char filename2[]={"output.txt"};
char a;
FILE *inptr, *outptr;
inptr = fopen(filename, "r");
if(inptr == NULL)
{
printf("The file could not be opened!\n");
system("pause");
return 1;
}
outptr = fopen(filename2, "w");
if(outptr == NULL)
{
printf("The file could not be opened!\n");
printf("Creating a new file......\n");
system("pause");
return 1;
}
while((fscanf(inptr, "%c", &a)) != EOF)
{
fprintf(outptr, "%c", a);
puts("A character was copied!\n\n");
}
fclose(inptr);
fclose(outptr);
system("pause");
return 0;
}
For example lets say there are 3 lines in the text file:
Hi
Bye
Hello
so I would need to copy the contexts to another file but it starts from:
Hello
Bye
Hi
Thanks!
In a method as follows in the case where there is sufficient memory can be read and processed files in memory.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
char *str;
struct node *next;
} Node;
Node *pushNode(Node *current, char *str){
Node *node = malloc(sizeof(Node));
if(node){
node->str = strdup(str);
node->next = current;
}
return node;
}
char *popNode(Node **current){
if(*current){
Node wk = **current;
free(*current);
*current = wk.next;
return wk.str;
}
return NULL;
}
#define MAXOFLINESIZE 1024
int main(){
char *str, buff[MAXOFLINESIZE];//max size include '\0'
Node *current = NULL;
FILE *inFile, *outFile;
inFile = stdin;//Mock
outFile = stdout;
while(NULL!=fgets(buff, sizeof(buff), inFile)){
current=pushNode(current, buff);//need check return of pushNode
}
while(NULL!=(str=popNode(&current))){
fprintf(outFile, "%s", str);
}
return 0;
}
You can read the lines from input file in forward direction. Can you think of any data structure where you can store the lines? The data structure should help you output the lines in reverse order.
I wouldn't read it char by char.
There are line by line reading functions in C, such as fgets().
So for each line, you could allocate a buffer, read the line into the buffer, and store a pointer to the buffer in an array. Once you're done. You go from the end of your array and output the stored strings.
The painful part about this is that C doesn't have dynamic arrays so you must emulate that (malloc, free), unless you know the maximum length of your lines and their maximum number beforehand.
Alternatively, there should be a way to do this without loading the whole file into memory (marking newline positions within your source file and then seeking to them in reverse order).

reading first line of a file in c

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)

Resources