fprintf not giving the values expected - c

I am trying to read numbers from multiple text files starting with 'numbers' and calculate the sum. I am getting some random numbers not contained in the file I am opening. I have tried initializing the array at 0 but that just made everything 0 on output.
This is the problem section I believe
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
DIR *d;
struct dirent *dir;
int fileAndSum(){
int sum = 0, i = 0;
int nums[100];
FILE* fptr = fopen(dir->d_name,"r");
fputs("11111111111111111", fptr);
for(i = 0; i <10; i++){
fscanf(fptr,"%d", &nums[i]);
printf("%d\n", nums[i]);
sum+=nums[i];
}
printf("%s\n", "----------sum--------------");
printf("%d\n", sum);
fclose(fptr);
The rest
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
DIR *d;
struct dirent *dir;
int fileAndSum(){
int sum = 0, i = 0;
int nums[100];
FILE* fptr = fopen(dir->d_name,"r");
for(i = 0; i <10; i++){
fscanf(fptr,"%d", &nums[i]);
printf("%d\n", nums[i]);
sum+=nums[i];
}
printf("%s\n", "----------sum--------------");
printf("%d\n", sum);
fclose(fptr);
}
int main(void) {
d = opendir("numdir");
char strhold[50] = "numbers";
char fileName[50];
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
if(strstr(dir->d_name, strhold)){
printf("%s%s%s\n", "----------Now reading ",dir->d_name,"--------------");
fileAndSum();
printf("%s\n", "----------Next file--------------");
}
}
closedir(d);
return(0);
}

Your files to read are in directory numdir, but you are trying to read files in current working directory.
Also you should check if file open is successful.
to fix, the part
FILE* fptr = fopen(dir->d_name,"r");
should be
char fileName[1024];
snprintf(fileName, sizeof(fileName), "numdir/%s", dir->d_name);
FILE* fptr = fopen(fileName,"r");
if(fptr == NULL){
puts("open failed");
return 0;
}

Related

Issue writing strings to a file

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define KEYSIZE 16
int main(){
FILE *fptr;
fptr = fopen("program.txt", "w");
if (fptr == NULL) {
printf("Error!");
exit(1);
}
int num_keys = 1524006529 - 1523999329;
const char *keys[num_keys];
int idx = 0;
int j;
for (j = 1523999329; j<= 1524006529; j++){
int i;
char key[KEYSIZE];
srand (j);
for (i = 0; i< KEYSIZE; i++){
key[i] = rand()%256;
printf("%.2x", (unsigned char)key[i]);
fprintf(fptr, "%.2x", (unsigned char)key[i]);
}
fprintf(fptr, "%s", "\n");
printf("\n");
keys[idx] = key;
idx ++;
}
fclose(fptr);
return 0;
}
I want to create a text file (program.txt) that has a new string key variable on each line. The code above produces a txt file that has this content though:
h?G??+?
Mp???+??
a?G????#*Jb`e0?H?????G??????
S6&}?Μ??G??OFf??|???s8f?G????ɼ???5q??(???K?G?? ??J????9?+???G?????cZ?n0?Jr?G?????#O9]??????jH??G???krT?̇)?A
?g?v?G??????h^(?^?
û/?G???^vB?~W?39???G??\????"?iJ_????G??p??>??????I???U?G????????:??o?RV???G??/?C?^?????|?۬?G??q#0.L$+??Nv?????G????u? L?Ϩ????dv?G??[??C「<??i???G??UyM??Ƭ/??CxXUě?G?????φ
׏:W&?G????=J???o???I??G???G%DA+"?~5?Z¡?G??øL#??O=e?b?u.O?G????*jjɥ+T?)?օ?G??2w }a,ȃ??tC?s?G??J"/c??Mn???f?y??G????p?Ay?c????~"<?G?????Ӆ?=%??#???G??o?\??<w???4WϚBE?G??}oh??(??#HK???&?G????Vfz
???e?s?G??/?Ye??iV?؛?,-te?G??I?Ҁx??5?B!b?4?G??6Z??9?P?GcB?}???Y?~|"??dd??G??????=?ms?
??G?????^??[H??\:???G??2(J??A??????G???????o#?i?/???G??P?5?5?5X??
What am I doing wrong here?

trying to write integers into file genreates random characters in C language

I'm trying to make a random input.txt file generator in C language but I keep getting random characters in the output file. I tried using both putw() and fwrite() but I get the same result.
for(int i = 0; i < 100; i++){
ran_numb = rand()%(ram_size-1);
// printf("%d", ran_numb);
// int err = putw(ran_numb, fp);
fwrite(&ran_numb, sizeof(int), 1, fp);
fputc('\n', fp);
}
output file:
~
ô
u
?
{
ø
È
Õ
å
×
¡
full code:
#include <stdio.h>
#include <string.h>
int main (int argc, char* argv){
generate_input_file(2048);
}
void generate_input_file(int ram_size){
int ran_numb = 0;
FILE *fp = fopen("input.txt", "w");;
if(fp == NULL){
printf("can't open file!");
}
for(int i = 0; i < 100; i++){
ran_numb = rand()%(ram_size-1);
// printf("%d", ran_numb);
// int err = putw(ran_numb, fp);
fwrite(&ran_numb, sizeof(int), 1, fp);
fputc('\n', fp);
}
}
After the help of the comments, this is the final program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include "simulator.h"
int main (int argc, char* argv){
generate_input_file(2048);
}
void Gen_Input_File(int ram_size){
int ran_numb = 0;
const char filename[] = "input.txt"
FILE *fp = fopen(filename, "w");;
if(fp == NULL){
fprintf(stderr, "Failed to open file '%s' for writing: %s\n", filename, strerror(errno));
exit(EXIT_FAILURE);
}
srand(time(NULL));
for(int i = 0; i < 10000; i++){
ran_numb = rand()%(ram_size-1);
fprintf(fp, "%d\n", ran_numb);
}
}
I've added the missing headers to stop warnings.

How to shuffle 2 different text file into 1?

#include <stdio.h>
int main(){
char temp[64];
FILE *fp1=fopen("data/1.txt","a");
FILE *fp2=fopen("data/2.txt","r");
while(fgets(temp,64,fp2)!=NULL){
fputs(temp,fp1);
}
fclose(fp1);
fclose(fp2);
return 0;
}
With such code I was able to combine 2 different text file into 1.
data/1.txt contents: abcdefghijk
data/2.txt contents: ABCDE
Outcome: abcdefghijkABCDE
However, I am struggling with shuffling 2 different text file.
Wanted result: aAbBcCdDeEfghijk
Followings are my current code.
#include <stdio.h>
#include <string.h>
int main(){
FILE *fp1,*fp2,*fp_out;
char ch1,ch2;
int result=1;
fp1=fopen("data/1.txt","r");
fp2=fopen("data/2.txt","r");
fp_out=fopen("data/out.txt","w");
//shuffling code area//
fclose(fp1);
fclose(fp2);
fclose(fp_out);
char buf[64]={};
fp_out=fopen("data/out.txt","r");
fgets(buf,64,fp_out);
if(!strncmp("aAbBcCdDeEfghijk",buf,64))
printf("PASS\n");
else
printf("FAIL\n");
fclose(fp_out);
return 0;
}
How can I design a code in "shuffling code area" in order to have outcomes like wanted result? I have thought about making 2 different FOR loops and combining but it kept showed an error.
This is some dirty way to do the job.
You can read the file which ever you want to write first character first and then read a character from second file and write both into third file one after the other.
Just adding extra code as per your need.
This just works for your case , not tested with many cases and corner cases.
#include <stdio.h>
#include <string.h>
int main(){
FILE *fp1,*fp2,*fp_out;
char ch1,ch2;
int result=1;
int file1_content_over = 0;
int file2_content_over = 0;
fp1 = fopen("data/1.txt","r");
fp2 = fopen("data/2.txt","r");
fp_out=fopen("data/out.txt","w");
//shuffling code area//
// read till file1_content_over or file2_content_over is not finished
while(! file1_content_over || !file2_content_over)
{
ch1 = fgetc(fp1);
ch2 = fgetc(fp2);
if(ch1 != EOF)
fputc(ch1,fp_out);
else
file1_content_over = 1;
if(ch2 != EOF)
fputc(ch2,fp_out);
else
file2_content_over = 1;
}
//shuffling code area//
fclose(fp1);
fclose(fp2);
fclose(fp_out);
char buf[64]={};
fp_out=fopen("data/out.txt","r");
fgets(buf,64,fp_out);
printf("buf = %s\n", buf);
if(!strncmp("aAbBcCdDeEfghijk",buf,strlen("aAbBcCdDeEfghijk")))
printf("PASS\n");
else
printf("FAIL\n");
fclose(fp_out);
return 0;
}
Working for me! Not the best optimized code, I didnt get to much time to that!
Main():
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 100
int removingSPaces(char array[MAX], int sizeArray);
void orderChar(char bufFile1[MAX], char bufFile2[MAX], char bufOut[MAX], int maxSize, int sizeBuf1, int sizeBuf2);
int getChar(char buf[MAX], FILE *fp);
int main(){
FILE *fp1, *fp2, *fpOut;
char bufFile1[MAX] = {0}, bufFile2[MAX] = {0}, bufOut[MAX] = {0};
int sizeBuf1 = 0, sizeBuf2 = 0;
int maxSize=0;
if((fp1=fopen("file1.txt","r")) == NULL || (fp2=fopen("file2.txt","r")) == NULL || (fpOut=fopen("fileOut.txt","w")) == NULL){
perror("");
exit(1);
}
sizeBuf1 = getChar(bufFile1, fp1); //geting the chars from file1
fclose(fp1);
sizeBuf1 = removingSPaces(bufFile1, sizeBuf1); //removing the \n if exists from chars of file1
sizeBuf2 = getChar(bufFile2, fp2); //geting the chars from file2
fclose(fp2);
sizeBuf2 = removingSPaces(bufFile2, sizeBuf2); //removing the \n if exists from chars of file2
maxSize = sizeBuf1 + sizeBuf2; //Max Size to loop for
orderChar(bufFile1, bufFile2, bufOut, maxSize, sizeBuf1, sizeBuf2); //Order the chars!
fprintf(fpOut, "%s", bufOut); //Printing to the file
fclose(fpOut);
/* COPIED FROM YOUR CODE */
char buf[64]={0}; //Just added the 0, because you cant initialize the array like with only {}
if((fpOut=fopen("fileOut.txt", "r")) == NULL){
perror("");
exit(1);
}
fgets(buf,64, fpOut);
if(!strncmp("aAbBcCdDeEfghijk", buf, 64))
printf("PASS\n");
else
printf("FAIL\n");
fclose(fpOut);
/* COPIED FROM YOUR CODE */
return 0;
}
Functions():
int removingSPaces(char array[MAX], int sizeArray){
int size = sizeArray;
if(array[sizeArray -1] == '\n'){
array[sizeArray -1] = '\0';
size = strlen(array);
}
return size;
}
int getChar(char buf[MAX], FILE *fp){
char bufAux[MAX];
int size;
while(fgets(bufAux, sizeof(bufAux), fp)){
size = strlen(bufAux);
}
strcpy(buf, bufAux);
return size;
}
void orderChar(char bufFile1[MAX], char bufFile2[MAX], char bufOut[MAX], int maxSize, int sizeBuf1, int sizeBuf2){
int positionsF1=0, positionsF2=0;
int aux = 0; //This will starts organization by the first file! If you want to change it just change to 1;
for(int i=0; i < maxSize; i++){
if(aux == 0 && positionsF1 != sizeBuf1){
bufOut[i]=bufFile1[positionsF1];
if(positionsF2!=sizeBuf2){
aux = 1;
}
positionsF1++;
}else if(aux == 1 && positionsF2 != sizeBuf2){
bufOut[i]=bufFile2[positionsF2];
if(positionsF1!=sizeBuf1){
aux = 0;
}
positionsF2++;
}
}
}
Content of file 1:
abcdefghijk
Content of file 2:
ABCDE

Read from a file and store it in 2d array

I am working on a function that reads from a file (fp) and stores in the words array. I declared MAX_WORD_SIZE as 128, but when I input any file into this function and check with valgrind, it tells me I have an uninitialized value in the line "while(getline(&line,&count,fp)!=-1)" I really don't get it: what is the uninitialised value? My fp file is valid and the word array is also declared well. Thank you in advance.
#include "functions.h"
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int read_file(FILE *fp, char words[][MAX_WORD_SIZE + 1], int size) {
int i=0;int j=0;
size_t count=MAX_WORD_SIZE;
char* line=malloc(MAX_WORD_SIZE);
while(getline(&line,&count,fp)!=-1){
for(;count>0;count--,j++){
sscanf(line,"%c",&words[i][j]);
}
i++;
}
int totalNums = i;
int totalNum = j;
if (i<size){
return 1;
}
fclose(fp);
return 0;
}
This is the function that I called this read_file function:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "functions.h"
int main(int argc, char *argv[]) {
const char* fileName = argv[1];
FILE *fp = fopen(fileName, "r");
if (fp == NULL) {
printf("Invalid input file\n");
return 1;
}
int size = 0;
int validity = fscanf(fp, "%d", &size);
int returnValue = 0;
char words[size][MAX_WORD_SIZE + 1];
if(validity != 1 || size <= 0) {
printf("The first line is not a valid number\n");
return 1;
}
returnValue = read_file(fp, words, size);
if (returnValue == 1) {
fclose(fp);
return 1;
}
return 0;
}

Trying to read from a file that I know exists and is good but will not open

When I try to open a file "canbus.txt.txt" it is coming back with an error message that reads out "error: No error" repeatedly. I cannot find where this issue would be coming from. My file is in the main project directory and the name and extensions are all correct.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int i;
char value;
char test[60];
char *line;
int num = 0;
int address[25];
int values[25];
void ms_delay (int N)
{
T1CON = 0x08030;
int delay = N * 62.5; // 1 Milisecond => .001 / (256 * (1/16,000,000)) = 62.5
TMR1 = 0;
while (TMR1 < delay);
}
int main (void)
{
PIN_MANAGER_Initialize();
UART1_Initialize();
ECAN1_Initialize();
ECAN1_ReceiveEnable();
INTERRUPT_Initialize();
FILE *fp;
char* filename = "canbus.txt.txt";
fp = fopen(filename, "r");
if(fp == NULL){
perror("Error");
exit(EXIT_FAILURE);
}
while(fgets(line, sizeof(line), fp)){
fscanf(fp, "%lf %lf", &address[num], &values[num]);
sprintf(test, "Value = %lf Other = %lf", address[num], values[num]);
int i = 0;
while(test[i] != '\0'){
UART1_Write(test[i]);
i++;
}
++num;
}
ms_delay(250);
UART1_Write(0x0D);
UART1_Write(0x0A);
fclose(fp);
return 0;
}
#include <stdio.h>
int main()
{
FILE *fr;
char c;
fr = fopen("prog.txt", "r");
while( c != EOF)
{
c = fgetc(fr); /* read from file*/
printf("%c",c); /* display on screen*/
}
fclose(fr);
return 0;
}
To know more https://www.codesdope.com/c-enjoy-with-files/

Resources