Read specific line from different text files in C programming - c

Alright so i'm still learning C programming and what im trying to do is read a specific line from different text files in the same folder. So what i mean to say is lets say i want to read the names from different text files and display them. Ive been trying to do it but im only able to read text from one file at a time
below is my code
void display_medicine()
{
system("cls");
const char *fil = "Medicines/";
const char *exec = ".txt";
char filename[50];
//snprintf(filename, sizeof filename, "%s%s%s", fil, medicineview, exec);
system("cls");
char medicinename[50];
char medavailability[20];
char companyname[100];
char dom[25];
char doe[50];
char price[20];
FILE *file;
file =fopen(filename,"r");
int num = 1;
if (file)
{
fgets(medicinename, sizeof(medicinename), file);
fgets(medavailability, sizeof(medavailability), file);
fgets(companyname, sizeof(companyname), file);
fgets(dom, sizeof(dom), file);
fgets(doe, sizeof(doe), file);
fgets(price, sizeof(price),file);
fclose(file);
gotoxy(10,3);
printf("================= %s VIEWING ================" "\n");
gotoxy(14,5);
printf("Name:\t\t\t%s", medicinename);
gotoxy(14,7);
printf("Availability:\t\t%s", medavailability);
gotoxy(14,9);
printf("Company Name:\t\t%s", companyname);
gotoxy(14,11);
printf("Date of Manufacture:\t%s", dom);
gotoxy(14,13);
printf("Date of Expiry:\t\t%s", doe);
gotoxy(14,15);
printf("Price:\t\t\t%s\n",price);
gotoxy(10,17);
printf("===============================================");
gotoxy(10,19);
printf("Press any key to go back!");
getch();
customerMenu();
}
Im able to read stuff only from one text file but not the others
Any help would be much appreciated

Related

How to write data to multiple files using arrays of pointers of file in C?

This is my code which I have written so far
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
char quit[4] = "exit";
// char *filearray[100];
char filearray[100][14];
FILE **originalfilearray;
int counter = 0;
//Copy part
while(1){
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
break;
printf("Cannot open file %s \n", filename);
exit(0);
}
strcpy(filearray[counter], filename);
originalfilearray[counter] = fptr1;
counter+=1;
}
//Paste part
for (int i = 0; i < counter; i++)
{
printf("Enter the filename to open for writing for file %s\n", filearray[i]);
scanf("%s", filename);
fptr2 = fopen(filename, "w");
// Read contents from file
c = fgetc(fptr2);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(originalfilearray[i]);
}
printf("\nContents copied to %s\n", filename);
}
}
The problem occurs when I run the paste code the file is created but no content is pasted.
I have already tried reading many post regarding array of pointers of file. Some suggested to create originalfilearray variable with a single pointer some with double.
The major problem I guess is with the copy part.
Can someone please help me with the part where I need to copy the data of multiple files in the originalfilearray variable
Thank You
Apart from not allocating memory for originalfilearray, which other user explained, here are some things you are doing wrong
In
c = fgetc(fptr2);
You are trying to get character from an empty file you just opened in
fptr2 = fopen(filename, "w");
what you should be doing is starting a file pointer fptr and opening
FILE *fptr=fopen(filearray[i], "r");
and then copying content into it with
while ((c = fgetc(fptr))!= EOF)
{
fputc(c, fptr2);
}

C language help:How to store strings from a .txt file into a character array? This .txt file is read from a command line argument btw.

I need to create a program that will read in a .txt file using the command line arguments and then encrypt the message in that txt file.
I used pointer to open the txt file and I opened it successfully. But I need to store the message (consists of many paragraphs) into an array of single characters so that I can start my encryption.
For example, if the message is: I love dogs
I want to store that message into an array of characters such as:
char word[5000];
char word[0] = I;
char word[1] = l;
char word[2] = o;
etc....
I tried to use a for loop to store the message into single character array, but when I tried to print out the array it does not show on my command line.
How can I store the message from the .txt file into a single character array?
this is my code:
int main(int argc, char*argv[])
{
int a;
printf("The number of arguements is :%d \n", argc);
for(a=0; a<argc; a++)
{
printf("argc %d is %s \n",a, argv[a]);
}
//This section uses file pointer to read from a text file and then display it
printf("\n");
char * fname= argv[1];
FILE *fptr= fopen(fname, "r");
char word[5000];
int c;
if (fptr==0)
{
printf("Could not open file\n");
}else
{
printf("FILE opened successfully \n");
}
while (fgets(word, 5000, fptr) !=NULL)
{
printf("%s \n", word);
}
fclose(fptr);
Your while loop uses fgets that is intended to read line by line. If you want an array of characters that represents the bytes of the file, use fread. First you'll need to know how big the file is; use stat or fstat for that.
#include <stat.h>
struct stat statbuf;
int FS;
char* buffer
if (fstat(fileno(fptr),&statbuf)){
... handle error
}
FS = statbuf.st_size;
Then, for the file size now in FS, allocate some bytes
buffer = (char*) malloc(FS)
Then read the contents
fread(buffer, 1, FS, fptr)

How can I open an existing file in Xcode in C?

I have created a file called mahmoud.txt in the direceotry: /Users/mahmoudhamra/Desktop/C language/
I want to open it in Xcode.
I created the directory and the name of the file into a string each.
Then I concatenated the file name to the directory and tried to open it to read it but it always gives me an error: "Thread 1: signal SIGBART".
Can someone help me please?
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char * argv[]) {
FILE *inFile;
char fileName[13];
printf("enter file name: ");
scanf("%s",fileName);
char new[40]="/Users/mahmoudhamra/Desktop/C language/";
strcat(new, fileName);
inFile=fopen("new", "r");
if (inFile== NULL) {
printf("file %s was not opened!\n", fileName);
printf("check that the file exists!\n");
exit(1);
}
else
printf("the files has successfully been opened!\n");
return 0;
}
First of all this
char new[40]="/Users/mahmoudhamra/Desktop/C language/";
should be at least
char new[41]="/Users/mahmoudhamra/Desktop/C language/";
to leave space for null terminator. A C-string is an array of chars with a null-terminator (0x00, '\0', 0) as last char.
Best would be:
char new[]="/Users/mahmoudhamra/Desktop/C language/";
BTW your problem is that you have no space to add filename chars, so at least you should define it as
char path_and_file[128] = {0};
strncpy(path_and_file, "/Users/mahmoudhamra/Desktop/C language/", sizeof(path_and_file)-1);
If you want to learn something about dynamic allocation you can:
char *directory = "/Users/mahmoudhamra/Desktop/C language/";
char *path_and_file = malloc(strlen(directory)+1);
if (path_and_file != NULL)
{
strcpy(path_and_file, directory);
printf("enter file name: ");
scanf("%s",fileName);
path_and_file = realloc(path_and_file,strlen(directory)+strlen(filename)+1);
if (path_and_file != NULL)
{
strcat(path_and_file, filename);
// YOUR STUFF
}
}
free(path_and_file);
Another way with dynamic allocation is using strdup to create your first string:
char *path_and_file = strdup("/Users/mahmoudhamra/Desktop/C language/");
EDIT
Last thing, as #visibleman pointed out, the call to fopen have to be changed to
inFile=fopen(new, "r");
or according to my examples:
inFile=fopen(path_and_file, "r");
The issue is almost certainly the size of the new character array as it does not have the capacity to hold the complete filename and will cause a stack overflow:
char new[40]="/Users/mahmoudhamra/Desktop/C language/";
strcat(new, fileName);
Change the 40 to 1024:
char new[1024] = ...;

Cannot copy one file to another file

While im studying C from a old book (that might be the problem), i wrote the code to copy the content of one file to another one.
But somehow, the program stops working. I would appreciate some help.
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
FILE *fin, *fout; //Pointers to the files
int ch;
if (argc!=3) //Just checking if the user inserted the correct information
{
printf("\nCorrect mode: Program name, file1 -> file2 \n\n");
exit(1);
}
fin=fopen(argv[1], "rb");
if (fin==NULL) //Checking if the file exists
{
printf("\n\nERROR!\n\nThe file you're trying to open does not exist or it cannot be opened.\n\n");
exit(2);
}
if ((fout=fopen(argv[2], "wb"))==NULL) // If it cannot create a file
{
printf("\n\nERROR!\n\nImpossible to create the file %s\n\n", argv[2]);
exit(3);
}
while ((ch=fgetc(fin))!=EOF)
fputs(ch, fout);
fclose(fin);
fclose(fout);
}
You are using fputs to write the characters. It is used for strings (arrays of char). Instead use fputc.

Reading a text file line by line and saving to an array (C Language)

Here's my issue:
I'm currently working on a project for university. We're suppose to do a program that receives .pbm and .pgm files as input, and then we're suppose to handle them in some ways. But for now the main thing is to successfully receive them.
Each .pbm and .pgm file's first line is a "magic number". A set of characters like P1, P2 (...) P6.
Our goal is to receive a .pbm file as input, save the first line, dynamically allocate a string so it is just as big as its content (P6\n, for example), so we can then detect the magic number. The same applies to every other line. We basically just want a way to save each line into an array, making them just as big as their content.
Me and my project partner are both beginners: file handling, pointers, dynamic memory and headers are still pretty hard to us. Thank you in advance.
---EDIT--- (Forgot the code, as an user pointed out)
int main(int argc, char const *argv[])
{
readFile(argv[1], "EI_2012-13_ascii.pbm");
return 0;
}
void readFile (const char* input_file, char* filename){
char *line_buffer, *line;
FILE *file_stream = NULL;
if(!check_extension(filename, ".pbm") &&
!check_extension(filename, ".pgm") && !check_extension(filename, ".ppm"))
ERROR(ERR_EXT, "Invalid file extension!\n");
file_stream = fopen(input_file, "r");
if (file_stream == NULL)
ERROR(ERR_EXT, "Couldn't open the file for reading");
line_buffer = malloc(sizeof(2));
fscanf(file_stream, "%s", line_buffer);
//line = strchr(line_buffer, '\n');
printf("%s\n", line_buffer);
printf("%d\n", sizeof(line_buffer));
fclose(file_stream);
}
With this code we were attempting to output a string and its size underneath it. Strangely we keep getting the same output: 4. We needed that the malloc received a proper argument, the size of the line until the '\n'.
You can detect the magic number reading the file line by line using Linux function getline() as shown below,
void readFile (const char* input_file, char* filename){
char *line;
FILE *file_stream = NULL;
ssize_t read; size_t len = 0;
file_stream = fopen(input_file, "r");
if (file_stream == NULL)
ERROR(ERR_EXT, "Couldn't open the file for reading");
while((read = getline(&line, &len, file_stream)) != 1){
printf("%s", line);
printf("length of line: %zu\n", read);
}
if (line)
free(line);
fclose(file_stream);
}

Resources