i wanna know why my program can't input the numbers of my .txt file them into my array. It reads them but i can't manage to input them into an array for later use.
Can anybody help me to understand better the management of reading and writing files in c, please i'm new at this topic, i know i'm supposed to use int instead of chars since my .txt file contains only numbers. But with the functions such as fgets is for chars only i think.
#include <stdio.h>
int main()
{
FILE* file;
char name[10] = "100.txt";
char line[10];
int n;
char i[5];
file = fopen(name, "rt");
if (file == NULL)
{
printf("There is no such file!\n");
return 0;
}
for (n=0; n < 100; n++){
fgets(line, 5, file);
//puts(line);
i[n]=line;
puts(i[n]);
}
fclose(file);
return 0;
}
if you switch to fscanf you can use int instead of char, and given that you are parsing a text file containing numbers it makes more sense. Assuming your 100.txt has 100 number separated by a whitespace this should work:
int main(int argc, char* argv[])
{
FILE* file;
char name[10] = "100.txt";
char line[10];
int n;
int numberArray[100];
file = fopen(name, "rt");
if (file == NULL)
{
printf("There is no such file!\n");
return 0;
}
for (n=0; n < 100; n++){
fscanf(file, "%d", &numberArray[n]);
}
fclose(file);
return 0;
}
Here is the link for an explanation of fscanf.
EDIT:
There is another, and more elegant solution, to use fscanf:
while (fscanf(file,"%d",&numberArray[n++]) == 1);
in that way you loop through your text file as long as there are numbers (i.e. until EOF). Be careful as the program could crash if the count of numbers in the text file is greater than the space allocated for the array.
For writing back to a file:
FILE* fp = fopen( "out_file.txt", "w" ); // Open file for writing
int arrNumSize = sizeof(numberArray) / sizeof(int);
for (int i = 0; i < arrNumSize; i++)
{
fprintf(fp, "%d", numberArray[i] );
}
fclose(fp);
Related
I'm new to C and I have to read data from a file, and I need to store that data in an array. I'm using FILE *fptr; fptr = fopen(¨filename.txt¨, ¨r¨) to read and fscanf(fptr,"%d", &num); to get the file data, however when compiling I only seem to get the memory location for it (I think? the file I'm using to try the code out has the number 5368 and I'm getting 6422296)
int main(void)
{
FILE *fptr;
fptr = fopen("example.txt" , "r");
if ((fptr = fopen("example.txt","r")) == NULL)
{
printf("Error! opening file");
exit(1);
}
int num;
fscanf(fptr,"%d", &num);
printf("VALUE OF NUM IS %d", &num);
fclose(fptr);
return 0;
}
Here a minimal example demonstrating reading a couple of numbers from filename.txt into an array num. You need to add error handling, and if you cannot fix the size (LEN) then either calculate it by figuring out how numbers is in the file, or realloc the size of the num array as needed:
#include <stdio.h>
#define LEN 2
int main() {
FILE *fptr = fopen("./filename.txt", "r");
int num[LEN];
for(int i = 0; i < LEN; i++) {
fscanf(fptr, "%d", num + i);
printf("%d\n", num[i]);
}
fclose(fptr);
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char* argv[]) {
char *filename = argv[1];
char *store = malloc(2);
FILE *fh = fopen(filename, "wb");
for(int i = 0; i < 100; i++) {
sprintf(store, "%u", i);
if (fh != NULL) {
fwrite (store, sizeof (store), 1, fh);
}
}
fclose (fh);
return 0;
}
I want my output to look like this -> https://imgur.com/a/nt2ly. The output it produces currently is all garabge.
The real reason for the garbage is the size of your data on the fwrite statement
fwrite (store, sizeof (store), 1, fh);
sizeof(store) is not the size of the string. It's the size of the pointer.
Aside, allocating 2 bytes for store is wrong. You're forgetting that a 2-digit number as a string needs space for a nul-terminator, so you're writing one char too many.
More minor issue: why testing the handle against NULL in the loop? you could exit in that case.
Also test the argument length (argc).
int main(int argc, char* argv[]) {
if (argc<2) exit(1); // protect against missing arg
char *filename = argv[1];
char store[50]; // use auto memory, faster & simpler, don't be shy on the size, don't shave it too close
FILE *fh = fopen(filename, "wb");
if (fh != NULL) { // test file handle here, not in the loop
for(int i = 0; i < 100; i++) {
// sprintf returns the number of printed chars, use this
// also use the proper format specifier for int
int nb_printed = sprintf(store, "%d", i);
// you may want to check the return value of fwrite...
fwrite (store, nb_printed, 1, fh);
}
fclose (fh);
return 0;
}
Note that this code will create a binary file with all numbers collated:
01234567891011...
so hardly useable. I would perform a sprintf(store, "%d ", i); instead to add spacing between the numbers.
Also note that if you wanted to write characters in a file, you'd be better off with:
fprintf(fh,"%d ",i);
(but I suppose the main point is to learn to use fwrite)
I'm writing a program in C, in which I am reading the data from a .txt file, and my goal is to put each element from the .txt file into an array. When I compile and run the program, the values of 50, 55, and 0 are returned. These are the ASCII values (I'm not sure why the elements are being stored as ASCII codes, but that's okay for now) for 2, 7, and 0 (meaning nothing was initialized since we reached the end of the .txt file. Why is my program not reading the .txt file from the beginning??
...
int main(int argc, char *argv[]){
FILE *inputFile;
char *input = argv[1];
char magicSquareArray[257];
inputFile = fopen(input, "r");
if (inputFile == 0){
printf("Cannot open file for reading!\n");
return -1;
}
fscanf(inputFile, "%s", magicSquareArray);
while (!feof(inputFile)){
fscanf(inputFile, "%s", magicSquareArray);
}
printf("%i\n", magicSquareArray[0]);
int sideSize = magicSquareArray[0];
int squareSize = sideSize * sideSize;
printf("%i\n", squareSize);
fclose(inputFile);
The text file:
3
4,3,8
9,5,1
2,7,6
Perhaps you want the code such as the following.
(However, I think in the following manner.
To prepare an array read the first number,
To assign a numerical value to read into it.)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
FILE *inputFile;
char *input = argv[1];
char magicSquareArray[257];
int ch, len;
inputFile = fopen(input, "r");
if (inputFile == 0){
printf("Cannot open file for reading!\n");
return -1;
}
len = 0;
while((ch = fgetc(inputFile)) != EOF && len < sizeof(magicSquareArray)-1){
magicSquareArray[len++] = ch;
}
magicSquareArray[len] = 0;
fclose(inputFile);
printf("%c\n", magicSquareArray[0]);
int sideSize = atoi(magicSquareArray);
int squareSize = sideSize * sideSize;
printf("%i\n", squareSize);
return 0;
}
For an assignment I'm trying to output multiple files with different names e.g. file_1.dat, file_2.dat etc. I was hoping I could do this the same way as fprintf and fscanf but that doesn't work.
What would anyone suggest (code below is what I used)
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i;
for( i = 0; i < 3; i++)
{
FILE *file;
file = fopen("testing_%d.dat", i,"w");
}
}
sprintf should come in handy.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i;
for( i = 0; i < 3; i++)
{
char buf[100]
FILE *file;
sprintf(buf, "testing_%d.dat", i);
file = fopen(buf, "w");
}
}
You can first write the file name to a char [] by using sprintf(), and then pass it to fopen().
char myFile[200];
sprintf(myFile, "testing_%d.dat", i);
file = fopen(myFile, "w");
file should be an array of FILE *. Also, fopen doesn't format a string like printf. Change your file opening logic to something like this:
#define NUM_FILES (3)
#define FILE_NAME_LENGTH (100)
FILE *pFileArr[NUM_FILES];
char filename[FILE_NAME_LENGTH];
for(i = 0; i < NUM_FILES; i++)
{
snprintf(filename, FILE_NAME_LENGTH, "testing_%d.dat", i);
pFileArr[i] = fopen(filename, "w");
}
I'm currently trying to make a program that will read a file find each unique word and count the number of times that word appears in the file. What I have currently ask the user for a word and searches the file for the number of times that word appears. However I need the program to read the file by itself instead of asking the user for an individual word.
This is what I have currently:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int num =0;
char word[2000];
char *string;
FILE *in_file = fopen("words.txt", "r");
if (in_file == NULL)
{
printf("Error file missing\n");
exit(-1);
}
scanf("%s",word);
printf("%s\n", word);
while(!feof(in_file))//this loop searches the for the current word
{
fscanf(in_file,"%s",string);
if(!strcmp(string,word))//if match found increment num
num++;
}
printf("we found the word %s in the file %d times\n",word,num );
return 0;
}
I just need some help figuring out how to read the file for unique words (words it hasn't checked for yet) although any other suggestions for my program will be appreciated.
If you want to print every line contained in the file just once, you have to save the strings you have read in a given data structure. For example, a sorted array could do the trick. The code might look as follow:
#include <stddef.h>
size_t numberOfLine = getNumberOfLine (file);
char **previousStrings = allocArray (numberOfLine, maxStringSize);
size_t i;
for (i = 0; i < numberOfLine; i++)
{
char *currentString = readNextLine (file);
if (!containString (previousStrings, currentString))
{
printString (currentString);
insertString (previousStrings, currentString);
}
}
You may use binary search to code the functions containString and insertString in an efficient way. See here for further informations.
You have to split your code into functions (subroutines).
One function would read the file and record all words; the other would count the number of occurrences for each word.
int main(int argc, char const *argv[])
{
char *words[2000];
// Read the file; store all words in the list
int number_of_words = ReadWords("words.txt", words, 2000);
// Now count and print the number of occurrences for each word
for (int i = 0; i < number_of_words; i++)
{
int n = CountOccurrences(words[i], "words.txt");
printf("we found the word %s in the file %d times\n", words[i], n);
}
// Deallocate dynamically allocated memory
Cleanup(words, number_of_words);
}
Note how the main function is relatively short. All the details are in the functions ReadWords and CountOccurrences.
To implement reading all words from a file:
int ReadWords(const char *filename, char *words[], int max_number_of_words)
{
FILE *f = fopen(filename, "rt"); // checking for NULL is boring; i omit it
int i;
char temp[100]; // assuming the words cannot be too long
for (i = 0; i < max_number_of_words; ++i)
{
// Read a word from the file
if (fscanf(f, "%s", temp) != 1)
break;
// note: "!=1" checks for end-of-file; using feof for that is usually a bug
// Allocate memory for the word, because temp is too temporary
words[i] = strdup(temp);
}
fclose(f);
// The result of this function is the number of words in the file
return i;
}
`#include <stdio.h>
#include <stdlib.h>
int main(int argc, char*argv[])
{
int num =0;
char word[2000];
char string[30];
FILE *in_file = fopen(argv[1], "r");
if (in_file == NULL)
{
printf("Error file missing\n");
exit(-1);
}
scanf("%s",word);
printf("%s\n", word);
while(!feof(in_file))//this loop searches the for the current word
{
fscanf(in_file,"%s",string);
if(!strcmp(string,word))//if match found increment num
num++;
}
printf("we found the word %s in the file %d times\n",word,num );
return 0;
}`
if any suggestion plz..most welcome
Blockquote