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");
}
Related
I have a function which writes a matrix using the printf() function. Is there a way to capture all the output of the matrix_output() function without having to each time re-open the file and append new content so that at the end, the content of file.txt is the following:
0 1 2
1 2 3
2 3 4
Here is the code:
/* main.c */
#include <stdio.h>
#include <stdlib.h>
void matrix_output();
void matrix_output() {
FILE *fp;
fp = fopen("file.txt", "w");
fclose(fp);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
FILE *fp;
fp = fopen("file.txt", "ab");
fprintf(fp, "%d\t", i+j);
fclose(fp);
}
FILE *fp;
fp = fopen("file.txt", "ab");
fprintf(fp, "\n");
fclose(fp);
}
}
int main() {
matrix_output();
return 0;
}
Indeed, as pointed out in the comment, I actually don't need to open and close the file each time:
/* main.c */
#include <stdio.h>
#include <stdlib.h>
void matrix_output(void);
void matrix_output(void) {
FILE *fp;
fp = fopen("file.txt", "w");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
fprintf(fp, "%d\t", i + j);
}
fprintf(fp, "\n");
}
fclose(fp);
}
int main() {
matrix_output();
return 0;
}
Re:
Is there a way to capture all the output of the matrix_output()
function without having to each time re-open the file and append new
content at the end?
Yes, by not closing the file. The write operation starts at the current file offset. After a successful write, the file's offset is updated by the number of bytes actually written.
So if you write 10 bytes to a file, the file's offset is updated by 10 bytes (assuming a successful write operation), and a subsequent write would start at that updated file offset.
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);
}
I desperately need some help with an exercise my professor gave me. Essentially, I'm making a program using a structure and dynamic memory where it'll read a file where each line has one word, and it'll print to a new file each unique word and how many times it was in the file.
So for instance, if the file going in had this
apple
orange
orange
The file it prints to would say
apple 1
orange 2
So far, this is my code
#include <stdio.h>
#include <stdlib.h>
struct wordfreq {
int count;
char *word;
};
int main(int argc, char *argv[]){
int i;
char *temp;
FILE *from, *to;
from = fopen("argc[1]","r");
to = fopen("argv[1]","w");
struct wordfreq w1[1000];
struct wordfreq *w1ptr[1000];
for(i = 0; i < 1000; i++)
w1ptr[i] = NULL;
for(i = 0; i < 1000; i++)
w1ptr[i] = (struct wordfreq*)malloc(sizeof(struct wordfreq));
while(fscanf(from,"%256s",temp)>0){
}
for(i = 999; i >= 0; i--)
free(w1ptr[i]);
}
w1ptr should store a word from the file in the wordfreq file, then increment count in that array. I have no clue how to go about storing the word in *word though. Any help would be greatly appreciated
This is how in general your read/write from a file
const int maxString = 1024; // put this before the main
const char * fn = "test.file"; // file name
const char * str = "This is a literal C-string.\n";
// create/write the file
puts("writing file\n");
FILE * fw = fopen(fn, "w");
for(int i = 0; i < 5; i++) {
fputs(str, fw);
}
fclose(fw);
puts("done.");
// read the file
printf("reading file\n");
char buf[maxString];
FILE * fr = fopen(fn, "r");
while(fgets(buf, maxString, fr)) {
fputs(buf, stdout);
}
fclose(fr);
remove(fn); // to delete a file
puts("done.\n");
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);
One of my functions reads lines from a text file and stores into a variable. I need a way to use that variable in my main function. I've tried several methods and nothing has worked. Can anyone help me?
#include <stdio.h>
#include <string.h>
int test(const char *fname, char **names){
char usernames[250][50];
FILE *infile;
char buffer[BUFSIZ];
int i =0;
infile = fopen(fname, "r");
while(fgets(buffer,50,infile)){
strcpy(usernames[i],buffer);
printf("%s",usernames[i]);
i++;
}
int x, y;
for(y = 0; y < 250; y++)
for(x = 0; x < 50; x++)
usernames[y][x] = names[y][x];
return 0;
}
int main()
{
char *names;
test("test.txt", &names);
}
Can anyone help? I haven't coded in C in a long time.
In C, the caller should allocate the memory for the strings it needs, otherwise, no one knows who's supposed to free memory. Then you can pass a pointer to a function that will populate it.
int main() {
char names[250][50];
test("test.txt", names);
for (int i=0; i < 50; i++) {
printf("File %d: %s", i, names[i], 250);
}
}
void test(const char *fname, char(*names)[50], int maxWords){
FILE *infile;
int i =0;
char buffer[50];
infile = fopen(fname, "r");
while(fgets(buffer,50,infile) && i < maxWords){
strcpy(usernames[i],names[i]);
i++;
}
}