Using fscanf to store words from file in an array - c

I am trying to write a program for some classwork that reads in a file using fscanf, and then stores each word into an array with one word in each element. Then I need to print each element of the array out on to a new line on the console.
The getty.txt file has the Gettysburg address in it with appropriate spacing, punctuation, and is multiline.
What I think is happening is that the entire text is being stored in the first element of the array, but I am not 100% sure as I am still learning to debug and write in C.
Any advice as to what I am doing wrong would be great! I currently only seem to be getting the last word and some extra characters.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void readFile();
void writeFile(char* buffer, int bufferlen);
FILE *fpread;
FILE *fpwrite;
char filebuffer[1000];
int filebufferlen = 0;
int main(int argc, char *argv[]) {
fpwrite = fopen("csis.txt", "w");
readFile();
writeFile(filebuffer, filebufferlen);
fclose(fpwrite);
return 0;
}
void readFile() {
char c;
filebufferlen = 0;
if(!(fpread = fopen("getty.txt", "r"))){
printf("File %s could not be opened. \n", "getty.txt");
fprintf(fpwrite,"File %s could not be opened. \n", "getty.txt");
exit(1);
}
while (!feof(fpread)) {
fscanf(fpread, "%s", filebuffer);
filebufferlen++;
}
}
void writeFile(char* filebuffer, int filebufferlen) {
for (int i = 0; i < filebufferlen; ++i){
printf("%c\n", filebuffer[i]);
}
}

After fixing the compile problems:
the code does not contain any code nor data declarations to contain an array of 'words.' So naturally, nothing but the last word is actually saved so it can be printed out.

Related

Copy lines from file to char *array[]?

Hi need a little bit of help here. I have a file with 5 lines and I want to put this lines into an array of type char *lines[5]; but I can't figure it out why the following isn't working.
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("name.txt", "r");
char *str;
char *list[5];
int i = 0;
while (fgets(str, 100, fp) != NULL) // read line of text
{
printf("%s", str);
strcpy(list[i], str);
i++;
}
}
As the commenters stated, you need to create an array (which is nothing more than a space in the memory) of a sufficient size to store your string. One approach to solve your problems is the following, note the comments:
#include <stdio.h>
#include <string.h>
int lines(FILE *file); //try to format the code according to some standard
int main(void) {
FILE *fp = fopen("name.txt", "r");
char list[5][100]; //make sure you allocate enough space for your message
// for loop is more elegant than while loop in this case,
// as you have an index which increases anyway.
// also, you can make sure that files with more than 5 lines
// do not break your program.
for(int i = 0; i<5 ;++i )
{
if(fgets(list[i], 100, fp) == NULL){
break;
}
//list[i] is already a string, you don't need an extra copy
printf("%s", list[i]);
}
}

How to use fscanf to read a text file including many words and store them into a string array by index

The wordlist.txt is including like:
able
army
bird
boring
sing
song
And I want to use fscanf() to read this txt file line by line and store them into a string array by indexed every word like this:
src = [able army bird boring sing song]
where src[0]= "able", src[1] = "army" and so on. But my code only outputs src[0] = "a", src[1] = "b"... Could someone help me figure out what's going wrong in my code:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *fp = fopen("wordlist.txt", "r");
if (fp == NULL)
{
printf("%s", "File open error");
return 0;
}
char src[1000];
for (int i = 0; i < sizeof(src); i++)
{
fscanf(fp, "%[^EOF]", &src[i]);
}
fclose(fp);
printf("%c", src[0]);
getchar();
return 0;
}
Pretty appreciated!
For example like this.
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define MAX_ARRAY_SIZE 1000
#define MAX_STRING_SIZE 100
int main(int argc, char *argv[]) {
FILE *fp = fopen("wordlist.txt", "r");
if (fp == NULL) {
printf("File open error\n");
return 1;
}
char arr[MAX_ARRAY_SIZE][MAX_STRING_SIZE];
int index = 0;
while (1) {
int ret = fscanf(fp, "%s", arr[index]);
if (ret == EOF) break;
++index;
if (index == MAX_ARRAY_SIZE) break;
}
fclose(fp);
for (int i = 0; i < index; ++i) {
printf("%s\n", arr[i]);
}
getchar();
return 0;
}
Some notes:
If there is an error, it is better to return 1 and not 0, for 0 means successful execution.
For a char array, you use a pointer. For a string array, you use a double pointer. A bit tricky to get used to them, but they are handy.
Also, a check of the return value of the fscanf would be great.
For fixed size arrays, it is useful to define the sizes using #define so that it is easier to change later if you use it multiple times in the code.
It's reading file one character at a time, Which itself is 4 in size like we see sizeof('a') in word able. Same goes for 'b' and so on. So one approach you can use is to keep checking when there is a space or newline character so that we can save the data before these two things as a word and then combine these small arrays by adding spaces in between and concatenating them to get a single array.

Print out first line of input file char by char, but nothing comes to screen

So Im trying to print out the first line of a file thats being passed in lets say its a plain text file with a couple of words in the first line.
I open the file and pass it through a function that does some work on the file called process. This little bit of work if for debugging reason , because my ultimate goal is to read in the entire text file line my line and process each line and reverse the words in that line.
But im stuck here i run the program with a text file argument and i get nothing in return and i know my logic sounds right i think? I just want this to ultimately printout every character in that line. Then eventually put all those characters in a char array or char instream[500]
Can someone tell me what iam doing wrong?
#include <stdio.h>
#include <stdlib.h>
void process(FILE *infile);
int main(int argc, char *argv[])
{
int i;
FILE *fp;
printf("argc = %d\n",argc);
for(i = 1 ; i <= argc; i++)
{
fp = fopen(argv[i], "r");
if(fp == NULL)
{
printf("The file: %s doesnt exist.\n", argv[i]);
}
else
{
printf("The file: %s does exist \n",argv[i]);
process(fp);
}
}
return 0;
}
void process(FILE *infile)
{
int k =0;
char iochar;
char instream[500];
while((iochar = getc(infile)) != '\n')
{
printf("Hi there %c", iochar ); // nothing prints out here why not??
//instream[k++] = iochar;
}
}

Array saving entire input file to one index? C

this might look familiar, but am having different problems come up, so I'm trying to ask a different question. My assignment is to read in a file like so:
AACTGGTGCAGATACTGTTGA
3
AACTGGTGCAGATACTGCAGA
CAGTTTAGAG
CATCATCATCATCATCATCAT
The first line is the original line I will testing the following ones against, with the second line giving the number of remaining lines. When I run the following code, it prints out my entire input file, but to the first index. So while I need each line to be a separate index to be able to call them, it isn't working out.
I assume I'm going wrong by having the defined LENGTH and ROW so big, but am unsure of any other way to save it line by line, especially since it is mixed (chars with a line of int in between). My problem here is also that I have no prior knowledge given of how long either the rows of "DNA" will be nor how many lines total.
For what it's worth: I was advised a few things but am still unsure how to literally implement them.
One of these was to first use fscanf with %s for the first line, then fscanf with %d for the second, and a loop of fscanf %s for the remaining lines. I've tried doing that, but couldn't get that to work properly either.
The second way I was given was "fgets() for the first line, fscanf() + fgetc() for the second line, and then a loop of fgets() for everything that remains." Again, I am unsure of how to implement this exactly.
Please and thank you!
Here's my code so far:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define LENGTH 125
#define ROW 125
struct dna{
char code [LENGTH];
};
int main(){
char filename[] = "input1.txt";
FILE *input = fopen("input1.txt","r");
char firstDna[LENGTH][ROW]={""};
int n=0,i=0,j;
makeArray(input,firstDna);
//closing file
fclose(input);
system("pause");
return 0;
}
void makeArray(FILE *input,char firstDna[LENGTH][ROW]){
int i,j;
for(i = 0; i < LENGTH; i++){
for(j =0; j < ROW; j++){
fscanf(input,"%c",&firstDna[i][j]);
printf("%c", firstDna[i][j]);
i++;
}
}printf("\n\n\n");
}
I implemented the first "advise" that you mentioned, fscanf with %s for the first line and fscnanf with %d for the second ...
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define LENGTH 125
#define ROW 125
struct dna{
char code [LENGTH];
};
void makeArray(FILE *input,char firstDna[LENGTH][ROW])
{
int i;
int remaining_lines;
fscanf(input,"%s\n",firstDna[0]);
printf("%s\n", firstDna[0]);
//scanning the number of remaing_lines
fscanf(input,"%d\n",&remaining_lines);
for(i = 1; i < LENGTH && i <= remaining_lines; i++)
{
fscanf(input,"%s\n",firstDna[i]);
printf("%s\n", firstDna[i]);
}
}
int main(){
char filename[] = "input1.txt";
FILE *input = fopen(filename,"r");
char firstDna[LENGTH][ROW];
makeArray(input,firstDna);
//closing file
fclose(input);
system("pause");
return 0;
}
hope this helps

How to read and compare character 255 in C

I need to write a code that searches all the aparition of a string in a file. Recently, my teacher told me to search string (char)255(char)255 in a file with the same string. The problem is that I can not read those characters and badly, I cannot distinguish or compare those caracter to EOF; My code for searching the given string in a file is :
//problema 14
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char b;
int k=0;
if(argc!=3) {
fprintf(stderr,"Utilizare: %s fisier sir\n",argv[0]);
return 1;
}
if(argv[2][0]=='\0'){
fprintf(stderr, "String vid\n");
return 1;
}
FILE *f;
f=fopen(argv[1],"r");
if (!f)
{
perror(argv[1]);
return 1;
}
int i=0;
while((b = fgetc(f))!=EOF)
{
if(b==argv[2][i]) i++;
else {
fseek(f,-i, SEEK_CUR);
i=0;
}
if(argv[2][i]=='\0'){
k++;
fseek(f,-i+1, SEEK_CUR);
i=0;
}
}
printf("\nSULFUS %d APPEARANCES\n",k);
return EXIT_SUCCESS;
}
what can I do with this code to work on comparint string of (char)255 characters?
The trick is to realize that fgetc returns an int.
So, change the data type of bto int!
But then, "while" does nothing, because it seems that 255 is also recognized as EOF or it goes infinite. I tried also with int but I couldn't figure out much...This teacher is like a compilator, he likes to put you in trouble.

Resources