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

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.

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?

Selecting random line from array c

So far I have read all my data into an array
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdlib.h>
int main(void) {
int i=0;
char* string[100];
char line[100];
FILE *file;
file = fopen("plates.txt", "r");
while(fgets(line, sizeof line, file)!=NULL) {
printf("%s",line);
string[i]=line;
i++;
}
fclose(file);
return 0;
}
but i want to now select a random line of my array and print it. All lines need to have an equal chance of being selected but they can only be selected once. Im not too sure how to do this...
Thank you in advance
Please be mindful of this line string[i]=line as it makes all the array entries in string that you set all point to the last line read which is not what you want and it's pretty important to understand that.
That said, here's a solution to the problem that assumes we can just store all the lines in memory and on the stack:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX_LINE_LENGTH 128
#define MAX_LINE_COUNT 1000
int main(int argc, char **argv) {
char lines[MAX_LINE_COUNT][MAX_LINE_LENGTH];
int numLines = 0;
if (argc < 2) {
fprintf(stderr, "missing file name\n");
return EXIT_FAILURE;
}
FILE *fp = fopen(argv[1], "r");
if (fp != NULL) {
while (fgets(lines[numLines++], MAX_LINE_LENGTH, fp)) {
printf("%03d> %s", numLines, lines[numLines-1]);
}
fclose(fp);
srand (time(NULL));
int randomIndex = rand() % numLines;
printf("Selected random line #%d> %s", randomIndex+1, lines[randomIndex]);
} else {
fprintf(stderr, "file '%s' not found\n", argv[1]);
return EXIT_FAILURE;
}
}
And the corresponding output:
➜ ~ gcc random-line.c && ./a.out random-line.c
001> #include <stdio.h>
002> #include <stdlib.h>
003> #include <string.h>
004> #include <time.h>
005>
006> #define MAX_LINE_LENGTH 128
007> #define MAX_LINE_COUNT 1000
008>
009> int main(int argc, char **argv) {
010> char lines[MAX_LINE_COUNT][MAX_LINE_LENGTH];
011> int numLines = 0;
012>
013> if (argc < 2) {
014> fprintf(stderr, "missing file name\n");
015> return EXIT_FAILURE;
016> }
017>
018> FILE *fp = fopen(argv[1], "r");
019> if (fp != NULL) {
020> while (fgets(lines[numLines++], MAX_LINE_LENGTH, fp)) {
021> printf("%03d> %s", numLines, lines[numLines-1]);
022> }
023> fclose(fp);
024> srand (time(NULL));
025> int randomIndex = rand() % numLines;
026> printf("Selected random line #%d> %s", randomIndex+1, lines[randomIndex]);
027> } else {
028> fprintf(stderr, "file '%s' not found\n", argv[1]);
029> return EXIT_FAILURE;
030> }
031> }
Selected random line #2> #include <stdlib.h>

fprintf not giving the values expected

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;
}

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/

Writing to a text file through the CMD window and a C exe?

I was wondering how I can get this code to overwrite a textfile from it's text value to it's ASCII value.
I want it to do something like this:
CMD > c:\users\username\desktop>cA5.exe content.txt
content.txt has "abc" in it and I want the command line to change the "abc" to it's ASCII values. 97... etc. I don't want anything written in the command window, I want it to change in the text file. Is this possible, if so, how could I do it with this existing code?
#include <stdio.h>
#include <stdlib.h>
int main(int argc[1], char *argv[1])
{
FILE *fp; // declaring variable
fp = fopen(argv[1], "rb");
if (fp != NULL) // checks the return value from fopen
{
int i;
do
{
i = fgetc(fp); // scans the file
printf("%c",i);
printf(" ");
}
while(i!=-1);
fclose(fp);
}
else
{
printf("Error.\n");
}
}
Not the best code but very simple.
#include <stdio.h>
#include <stdlib.h>
void convertToAHex(char *data, long int size, FILE *file){
rewind(file);
int i;
for(i = 0; i < size; ++i){
fprintf(file, "%d ", data[i]);
}
}
int main(int argc, char *argv[]){
if(argc != 2){
return EXIT_FAILURE;
}
FILE *file = fopen(argv[1], "r+");
if(file){
char *data;
long int size;
fseek(file, 0, SEEK_END);
size = ftell(file);
rewind(file);
data = (char *) calloc(size, sizeof(char));
if(data){
fread(data, 1, size, file);
convertToAHex(data, size, file);
free(data);
}
fclose(file);
}
return EXIT_SUCCESS;
}

Resources