remove() function doesn't work as expected - c

I am working with a code that generates a fixed number of files and keeps that number. After every new file is created, an old one has to be deleted. This is the code:
#include <stdio.h>
#include <stdlib.h> // needed for malloc
#include <string.h> // needed for strcpy
#include <unistd.h>
#define Extension ".txt"
#define LOG_MIN_FILENAME_SIZE 32
#define NBR_OF_FILES 6
char buffer[LOG_MIN_FILENAME_SIZE];
int timez = 0;
int minutes = 0;
int count = 0;
FILE* pf = NULL;
char* ListOfFiles[6];
int main(void)
{
for (int i = 0; i < 3; i++) {
ListOfFiles[i] = calloc(LOG_MIN_FILENAME_SIZE + 1, 1);
}
for (int i = 0; i < 10; i++) {
sprintf(buffer, "%d" "%d" Extension, minutes, timez);
if (access(buffer, F_OK) == -1) {
pf = fopen(buffer, "w"); // create the file
count++;
fclose(pf); //closing the files is necessary
if (count >= NBR_OF_FILES) {
remove(ListOfFiles[0]); //remove the oldes file.
}
for (int i = 0; i < NBR_OF_FILES - 1; i++) {
strcpy(ListOfFiles[i], ListOfFiles[i + 1]); // u cant use just normal assignment because it copies the head ot the pointer rather than the actual content of it
}
strcpy(ListOfFiles[NBR_OF_FILES - 1], buffer);
}
timez++;
minutes++;
}
for (int i = 0; i < NBR_OF_FILES - 1; i++) {
printf("%s", ListOfFiles[i]);
}
}
In the output, I get only one file created at a time (with every execution). When I execute the program more than NBR_OF_FILE times, no files are deleted! Do you have any idea that what the issue could be?

Related

How to input data from a text file into a pointer array?

I have a text file I want to upload into a pointer array but I can't find any references besides 2D arrays or languages other than C.
My input.txt:
marbels
fruit
vegetables
marshmellow sprinkle
coffe beans
My source.c (my question is located in the int main(void){})
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define MAX_LEN 1000
void sort(size_t size, char* data[]) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (strlen(data[j]) < strlen(data[j + 1])) {
char* temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
}
}
void printArray(size_t size, char* data[]) {
for (int i = 0; i < size; i++) {
printf("%s ", data[i]); //%c -> %s
}
}
int main(void) {
char* data[1000]; //I want the array to hold maximum 1000 characters
FILE* file;
file = fopen("C:\\Users\\EXAMPLE\\desktop\\input.txt", "r");
if (file == NULL) {
printf("File Error\n", file);
return 1;
}
//between these dashes in my issue with uploading the text from input to the char* data[1000];
int line = 0;
//if i build the program with this while-loop, I get an error
while (!eof(file) && ferror(file)) {
if (fgets(data[line], MAX_LEN, file) != NULL) { //error C6001: using uninitialized memory 'data'
line++;
}
}
fclose(file);
//
size_t size = sizeof data / sizeof data[0];
sort(size, data);
printArray(size, data);
return 0;
}
The error message:
I tried that while loop before and it wasn't great but only thing I could find at the time for this project.
As you have mentioned in your question, you will need to use a 2D array or otherwise you can use the malloc() function.
In your code you have a array with 1000 * sizeof(char) bytes. So bassically you have 1000 uninitialised pointers. But there are no pointers allocated that are able to store the lines of the file.

Program doesn't work after it loops the second time

My program below is trying to add the usernames from the "Usernames.text" to the API url. The first username works and makes the url "https://api.1234ng.com/users/profiles/planeraft/Username1" but once it loops back it makes the url always "https://api.1234ng.com/users/profiles/planeraft/" instead of adding the next username in the file.
My code:
#include <stdio.h>
#include <string.h>
int Counter;
int UsernameSize;
char Username[255];
char Request[255]="https://api.1234ng.com/users/profiles/planeraft/";
FILE *UsernamesFile;
int main() {
UsernamesFile = fopen("Usernames.text", "r");
while (Counter < 100) {
fgets(Username, 255, UsernamesFile);
UsernameSize = strlen(Username);
for (int z; z < UsernameSize; z++) {
Request[48 + z] = Username[z];
}
printf("%s", "\n");
printf(Request);
for (int a; a < UsernameSize; a++) {
Request[48 + a] = '\0';
}
Counter++;
}
fclose(UsernamesFile);
return 0;
}
Variables a and z in the for loops are not initialized and thanks to DiKetarogg for some improvements to the code.
Several errors fixed below, more improvements are possible, see comments above and in code below:
#include <stdio.h>
#include <string.h>
int Counter = 0; // need to init
int UsernameSize;
char Username[255];
char Request[255]="https://api.test.com/users/profiles/test/";
// 01234567890123456789012345678901234567890
// 1 2 3 4
FILE *UsernamesFile;
int main() {
UsernamesFile = fopen("Usernames.text","r");
while(Counter < 3) {
fgets(Username, 255, UsernamesFile);
strcat(Request, Username);
UsernameSize = strlen(Username);
Username[UsernameSize-1] = '\0'; // remove <cr>
for(int z=0; z < UsernameSize; z++) {
Request[41+z]=Username[z];
}
printf("%s\n", Request);
Counter++;
strcpy(Request, "https://api.test.com/users/profiles/test/");
}
fclose(UsernamesFile);
return 0;
}

Printing randomly to the screen in C

I am trying to print to the screen randomly in C. I am using random and time to generate random index and printing it but It definetely is not the way to do it. How do I print every element randomly to the screen in c?
Here is the code I have so far.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define leng 128
#define arr 10
int main(void)
{
char line[arr][leng];
char fname[20];
FILE *fptr = NULL;
int i = 0;
int tot = 0;
scanf("%s",fname);
fptr = fopen(fname, "r");
while(fgets(line[i], leng, fptr))
{
line[i][strlen(line[i]) - 1] = '\0';
i++;
}
srand(time(0));
for(int i = 0; i < 6; ++i)
{
printf("%s\n", line[rand()%10]);
}
return 0;
}
My random text file has 6 lines of code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define LEN 128 //Don't mind the capital, personal preference for defines
#define ARR 6 //Make this match the number of lines in your file
int main(void)
{
char line[ARR][LEN];
char fname[20];
int test[ARR] = {0}; //Added an array to test if index already created
int ind[ARR] = {0}; //Array to store index created randomly
int ind_done = 0; //Counter for index array
FILE *fptr = NULL;
int i = 0;
int tot = 0;
scanf("%s",fname);
fptr = fopen(fname, "r");
while(fgets(line[i], LEN, fptr))
{
line[i][strlen(line[i]) - 1] = '\0';
i++;
}
srand(time(0));
for(int i = 0; i < ARR; ++i)
{
printf("%s\n", line[rand()%ARR]);
}
//Keep creating indexes using rand till all unique indexes are created
while (ind_done<ARR) {
int i = rand()%ARR;
if (test[i] == 0) {
ind[ind_done] = i;
ind_done++;
test[i] = 1;
}
}
for(int i = 0; i < ARR; ++i)
{
printf("%s\n", line[ind[i]]);
}
return 0;
}

using while loop does not save data to file in c

I want take input from user and then save that input into the file. In my below code if I remove my while loop then the file is appended but I want this loop so that user can enter data upto 500 characters.
int main()
{
char Buffer1[5];
FILE *ot;
fopen_s(&ot, "D:\\export1.txt", "a+");
fseek(ot, 0L, SEEK_END);
int sz = ftell(ot);
printf("Enter Data.\n");
while (sz<500) {
for (int i = 0; i < 5; i++) {
scanf_s("%c", &Buffer1[i]);
}
// write data to file
for (int i = 0; i < 5; i++) {
fputc(Buffer1[i], ot);
}
sz = ftell(ot);
}
fclose(ot);
_gettch();
return 0;
}
This implementation only works if the user appends exactly the amount of bytes necessary to make 500 bytes in total.
It might be easier to first check the filesize, then let the user enter at most 500 - filesize characters, and only after that append the userinput to the file.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <conio.h>
#define ARRAY_LIMIT 10
int main()
{
char array[ARRAY_LIMIT];
int i = 0;
FILE *ot;
fopen_s(&ot, "export1.txt", "a+");
fseek(ot, 0L, SEEK_END);
int sz = ftell(ot);
printf("Enter Data.\n");
while (sz < 500)
{
while (i < ARRAY_LIMIT)
{
array[i] = getch();
printf("%c", array[i++]);
}
i = 0;
fwrite(array, sizeof(array), 1, ot);
sz = ftell(ot);
//be on the safe side...
if (sz != 500 && 500 - sz < ARRAY_LIMIT)
i = ARRAY_LIMIT - (500 - sz);
}
fclose(ot);
return 0;
}

Function keeps crashing without error message

Hello I am taking an intro to C-programming class so I am using very basic codes. Here I am simply trying to get a matrix of the commas out of the main string. However when I try running the program it keeps crashing on me and I don't know what is my problem. I was able to use the fgets function correctly so I think that is working fine still.
CD Data.txt File
Eagles, Hotel California, 1976, Rock, 4
The Fratellis, Costello Music, 2006, Garage Rock, 5
Awolnation, Megalithic Symphony, 2011, Indie Rock, 5
Lindsey Stirling, Lindsey Stirling, 2012, Classical Crossover, 5
Arctic Monkeys, AM, 2013, Indie Rock, 4
Program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define row 1000
#define column 1000
void getCommas(char str[], int commas[])
{
int flag, count, index;
count = 0;
index = 0;
flag = 1;
while(flag = 1)
{
if(str[count] = ',')
{
commas[index] = count;
index = index + 1;
}
count = count + 1;
if(str[count] = '\0')
{
flag = 0;
}
}
}
int main()
{
int i;
char CdInfo[row][column];
int Index[row][column];
FILE *fp;
fp = fopen("CD Data.txt","r");
for(i=0; i<5; i++)
{
fgets(CdInfo[i], sizeof CdInfo, fp);
//printf("%s\n",CdInfo[i]);
}
for (i=0; i<5; i++)
{
getCommas(CdInfo[i], Index[i]);
}
fclose(fp);
return 0;
}
These two variables are too big to be on the stack:
int main()
{
int i;
char CdInfo[row][column]; //<<
int Index[row][column]; //<<
declare them as static or as global variables.
And:
while(flag = 1)
should be
while(flag == 1)
and all
if (str[count] = ...
should be
if(str[count] == ...
You should also think about replacing
while(flag = 1) {
with :
while(flag == 1)
// note:
// the code is not making any use of more than one line of the
// input file at any one time, so
// only the current row actually needs to be defined
// note:
// this code makes no check for max length of each row (1000 char)
// that could/will be a problem when the input line is longer than 1000 character
// to avoid the error of writing an assignment rather than a literal,
// place the literal on the left side,
// then the compiler will notify you of the error
// rather than you having to spend time debugging the code
// trying to find the error
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define row 1000
#define column 1000
//void getCommas(char str[], int commas[])
void getCommas( char * pStr, int * pCommas )
{
//int flag, count, index;
//count = 0;
//index = 0;
//flag = 1;
int flag = 1;
int count = 0;
int index = 0;
//while(flag = 1)
// following while loop could eliminate
// the 'flag' variable and related code by using
// and would be safer because never looking at string termination
// character but once.
// while( '\0' != pStr[count] )
while( 1 == flag )
{
//if(str[count] = ',')
if( ',' == pStr[count] )
{
pCommas[index] = count;
index = index + 1;
}
count = count + 1;
//if(str[count] = '\0')
if( '\0' == pStr[count] )
{ // then found end of string
flag = 0;
}
}
}
char CdInfo[row][column];
int Index[row][column];
int main()
{
int i = 0;
int rowCount = 0;
//char CdInfo[row][column]; // this is a huge item on the stack,
//int Index[row][column]; // this is a huge item on the stack,
//FILE *fp;
FILE *fp = NULL;
fp = fopen("CD Data.txt","r");
// always check the result of calls to io functions
if ( NULL == fp )
{ // then fopen failed
perror( "fopen" );
exit(1);
}
// implied else
// there is no reasonable reason (in the real world)
// to expect the input to be only 5 lines
//for(i=0; i<5; i++)
//{
// fgets(CdInfo[i], sizeof CdInfo, fp);
// //printf("%s\n",CdInfo[i]);
//}
for( i=0; i<row; i++ )
{
// following line checks results of call to I/O function
if( 0 == fgets( CdInfo[i], row, fp ) ) { break; }
// above line exits loop on end of file or I/O error
rowCount++;
}
//for (i=0; i<5; i++)
for( i = 0; i < rowCount; i++ )
{
getCommas(CdInfo[i], Index[i]);
}
fclose(fp);
return 0;
}

Resources