How do i define a custom file path in c? - c

I'm trying to make it so a file name which is created using character arrays and strcat is created in a folder which is also created using character arrays and strcat. However, when I try to define the file path in the fopen() function, it refuses to compile.
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
char spaceadder (char array[100]) {
int i, count = -1;
for(i = 0; array[i] != '\0'; i++) {
count++;
}
array[count + 1] = ' ';
array[count + 2] = '\0';
return array;
}
int main(void) {
char make[50], model[50], reg[100], folderName[100], fileName[100];
FILE *fp;
printf("Reg: ");
scanf("%s", reg);
printf("Enter the Make and Model of the Vehicle: ");
scanf("%s %s", make, model);
strcpy(folderName, make);
spaceadder(folderName);
strcat(folderName, model);
spaceadder(folderName);
strcat(folderName, reg);
mkdir(folderName, 0777);
strcpy(fileName, "AD ");
strcat(fileName, reg);
fp = fopen(folderName\\fileName, "w");
fclose(fp);
return 0;
}

Related

Strange characters when reading from file in C

So I am just trying to learn C and have decided to program a simple calendar where you can add events etc. It is working almost perfectly however, when it tries to read from the file containing the information, the first line contains some strange characters : �<�}�U1.
Code is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void createCalendar(char filename[]) {
FILE *cptr;
cptr = fopen(filename, "w");
char dates[177/sizeof(char)] = "";
for(int i = 1; i < 32; i++) {
char strtowrite[7/sizeof(char)] = "";
sprintf(strtowrite, "%d - \n", i);
strcat(dates, strtowrite);
}
fprintf(cptr, "%s", dates);
fclose(cptr);
}
void addToDay(char filename[], int day, char event[]) {
FILE *cptr;
cptr = fopen(filename, "r");
char *line = NULL;
size_t len = 0;
ssize_t read;
char dates[177/sizeof(char) + strlen(event)/sizeof(char)];
int i = 1;
while ((read = getline(&line, &len, cptr)) != -1) {
if (i==day) {
char strtowrite[7/sizeof(char) + strlen(event)/sizeof(char)];
sprintf(strtowrite, "%d - %s\n", i, event);
strcat(dates, strtowrite);
}
else {
strcat(dates, line);
}
i += 1;
}
printf("%s", dates);
fclose(cptr);
cptr = fopen(filename, "w");
fprintf(cptr, "%s", dates);
fclose(cptr);
}
int main() {
createCalendar("january");
addToDay("january", 12, "event");
}
and the first line of output is: í¬_<89>lU1 - (in the file)
Try this
char dates[177/sizeof(char) + strlen(event)/sizeof(char)] = {0};
in your addToDay function when declaring the dates variable. I think that you do not set the memory there, so there might be some junk in that memory location.

Printing 2d Array with unknown number of strings in C

I have written a small program to read in a series of strings from a file and then to store them in a 2D Arrray. The strings are read into the array correctly, yet my program is not countering the number of rows in the file like I had expected.
I am honestly at a loss and cannot figure out why the program is not counting the rows in the file. Any explanation as to what I am doing wrong is greatly appreciated.
Here is the code that I have so far:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE* fp;
char nameArray[20][120], str[20];
int i = 0, j = 0, n;
int count = 0;
char name[20]; //filename
int ch;
printf("Please enter a file name: ");
scanf("%s", &name);
fp = fopen(name, "r");
if (fp == NULL) {
printf("File \"%s\" does not exist!\n", name);
return -1;
}
while (fscanf(fp, "%s", str) != EOF)
{
strcpy(nameArray[i], str);
i++;
}
while ((ch = fgetc(fp)) != EOF) {
if (ch == '\n')
count++;
}
for (i = 0; i<=count; i++)
{
printf("%s", nameArray[i]);
}
fclose(fp);
return 0;
}

storing a text file into array but it only prints out the last line

When I want to try to store some lines in the array from the text file it only prints the last line of the text file many times.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fp;
char str[1000];
char a[3][1000];
fp = fopen("filename.txt", "r");
if (fp == NULL) {
printf("Could not open file ");
return 1;
}
while (fgets(str, 1000, fp) != 0) {
printf("%s", str);
}
for (int i = 0; i <= 3; i++) {
strcpy(a[i], str);
printf("\n%s\n", a[i]);
}
fclose(fp);
return 0;
}
my text file
stan nu'est
nu'est stan
nu'est ot5
minhyun is a nu'est member
It only prints minhyun is a nu'est member 3 times.
Can someone please help me?
while (fgets(str, 1000, fp) != 0) {
printf("%s", str); //
}
stan nu'est
nu'est stan
nu'est ot5
and then after the end of while loop the str will store only the last line, which is
minhyun is a nu'est member
int the below written for loop, minhyun is a nu'est member will be copied to the a[i] for 4 times and printed.
for(int i = 0; i <= 3; i++){
strcpy(a[i], str);
printf("\n%s\n", a[i]);
}
to Copy the entire text to the array str, you may use below given code,
char kr;
int i=0;
do{
kr=fgetc(fp);
str[i++]=kr;
}while(kr!=EOF);
str[i]='\0';
and, to read the first three line of the text into the str array in order, you can use below given code.
int j=0,k;
for(i=0;i<3;i++,j++)
{
for(k=0;str[j]!='\n'&&str[j]!='\0';j++,k++)
a[i][k]=str[j];
a[i][k]='\0';
printf("\n%s\n", a[i]);
}
Here is the entire code below,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fp;
char str[1000];
char a[3][1000];
fp=fopen("filename.txt","r");
if(fp == NULL)
{
printf("Could not open file ");
return 1;
}
char kr;
int i=0;
do{
kr=fgetc(fp);
str[i++]=kr;
}while(kr!=EOF);
str[i]='\0';
int j=0,k;
for(i=0;i<3;i++,j++)
{
for(k=0;str[j]!='\n'&&str[j]!='\0';j++,k++)
a[i][k]=str[j];
a[i][k]='\0';
printf("\n%s\n", a[i]);
}
fclose(fp);
return 0;
}

Replace a word in C

can you advice me? I have a string from a file. When i see the string on my console, i need to write the word on which i want to change, and output the result in another file. For example: "Hello my girl" the word i want change "girl" on another word "boy". I can use the library
Can you advice me the algorithm which helps me to change the word?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char my_string[256];
char* ptr;
FILE *f;
if ((f = fopen("test.txt", "r"))==NULL) {
printf("Cannot open test file.\n");
exit(1);}
FILE *out;
if((out=fopen("result.txt","w"))==NULL){
printf("ERROR\n");
exit(1);
}
fgets (my_string,256,f);
printf ("result: %s\n",my_string);
ptr = strtok (my_string," ");
while (ptr != NULL)
{
printf ("%s \n",ptr);
ptr = strtok (NULL," ");
}
char old_word [10];
char new_word [10];
char* ptr_old;
char* ptr_new;
printf ("Enter your old word:\n");
ptr_old= gets (old_word);
printf ("Your old word:%s\n",old_word);
printf ("Enter new old word:\n");
ptr_new = gets (new_word);
printf ("Your new word:%s\n",new_word);
fclose(f);
fclose(out);
return 0;
}
i tried to split inputting string into words. Now its dead end.
This code will help you. you have to pass 4 args at runtime.
./a.out "oldword" "newword" "file name from take the old word" "file name where to copy"
$ ./a.out girl boy test.txt result.txt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int args, char *argv[4])
{
FILE *f1;
FILE *f2;
char *strings=0;
char *newstrings=0;
char *token=NULL;
strings=(char *)malloc(1000);
newstrings=(char *)malloc(1000);
if((strings==NULL)||(newstrings==NULL))
{
printf("Memory allocation was not successfull.");
return 0;
}
if(args<4)
{
puts("Error: Not enough input parameters");
puts("Usage: ./change <oldword> <newword> <infile> <newfile>");
return 0;
}
f1=fopen(argv[3],"r");
f2=fopen(argv[4],"w");
if(f1==NULL)
{
puts("No such file exists");
return 0;
}
while(fgets(strings,1000,f1)!=NULL)
{
if(strstr(strings,argv[1])!=NULL)
{
token=strtok(strings,"\n\t ");
while(token!=NULL)
{
if(strcmp(token,argv[1])==0)
{
strcat(newstrings,argv[2]);
strcat(newstrings," ");
}
else
{
strcat(newstrings,token);
strcat(newstrings," ");
}
token=strtok(NULL,"\n\t ");
}
}
else
{
strcpy(newstrings,strings);
}
fputs(newstrings,f2);
}
free(strings);
free(newstrings);
printf("New file <%s> generated!\n",argv[4]);
fclose(f1);
fclose(f2);
return 0;
}
You can use a function like the shown function in the demonstrative program below
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char * replace(const char *s, const char *src, const char *dsn)
{
size_t n = 0;
size_t src_len = strlen(src);
size_t dsn_len = strlen(dsn);
for (const char *p = s; (p = strstr(p, src)) != NULL; p += src_len)
{
n++;
}
char *result = malloc(strlen(s) + n * (src_len - dsn_len) + 1);
const char *p = s;
char *t = result;
if (n != 0)
{
for (const char *q; (q = strstr(p, src)) != NULL; p = q + src_len)
{
memcpy(t, p, q - p);
t += q - p;
memcpy(t, dsn, dsn_len);
t += dsn_len;
}
}
strcpy(t, p);
return result;
}
int main( void )
{
char s[] = " the girl and boy are relatives";
char *p = replace(s, "girl", "boy");
puts(s);
puts(p);
free(p);
}
The program output is
the girl and boy are relatives
the boy and boy are relatives
#include <stdio.h>
#include <string.h>
int main ()
{
char file_path[40] = { 0 }, stf[255] = { 0 }, rtf[255] = { 0 }, str[255] = { 0 };
FILE* file = NULL;
FILE *e_f;
if((e_f=fopen("result.txt","w"))==NULL){
printf("ERROR\n");
exit(1);
}
do
{
printf("Enter file path: ");
fgets(file_path, 40, stdin);
file_path[strlen(file_path) - 1] = '\0';
file = fopen(file_path, "r+");
}
while(file == NULL);
printf("Enter text to find: ");
fgets(stf, 255, stdin);
stf[strlen(stf) - 1] = '\0';
printf("Enter text to replace: ");
fgets(rtf, 255, stdin);
rtf[strlen(rtf) - 1] = '\0';
while(fgets(str, 255, file) != NULL)
{
char* tmp_ptr = strstr(str, stf);
while(tmp_ptr != NULL)
{
char tmp_str[255];
strcpy(tmp_str, tmp_ptr + strlen(stf));
strcpy(str + strlen(str) - strlen(tmp_ptr), rtf);
strcat(str, tmp_str);
tmp_ptr = strstr(str, stf);
}
printf("%s", str);
}
fclose(file);
fclose(e_f);
return 0;
}
That was i need. Thanks everybody for helping!
I did a function:
#include <stdio.h>
#include <string.h>
#define MAX 50
void Change (char x[], char cx, char nu){
int i;
for(i=0;i<strlen(x);i++) {
if (x[i]==cx){
x[i] = nu;
}
}
}
int main () {
char str[MAX];
char ch;
char new;
printf("Insert the string\n");
scanf("%s",str);
printf("Insert the word that you want to change\n");
scanf(" %c",&ch);
printf("the new word\n");
scanf(" %c",&new);
Change(str, ch, new);
printf("The new word is %s\n",str );
return 0;
}

Replace a word in a text file, then output the overwritten version

For this problem I'm asked to first read from the input text file, prompt the user which word/string to get replaced, then output the same file (the original gets overwritten). The thing is the input/outputfile name must always have a specific name for example test.txt (this is what bothers me)
Here's the function which I tested out and it does the job replacing, but for now I'm prompting user to enter their own "sentence" and then for words. I'm lost on how to (always) read from a test.txt and then output the same one with replaced string.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *w_replace(const char *s, const char *oldone, const char *newone)
{
char *ret;
int i, count = 0;
int newlen = strlen(newone);
int oldonelen = strlen(oldone);
for (i = 0; s[i] != '\0'; i++)
{
if (strstr(&s[i], oldone) == &s[i])
{
count++;
i += oldonelen - 1;
}
}
ret = (char *)malloc(i + count * (newlen - oldonelen));
if (ret == NULL)
exit(EXIT_FAILURE);
i = 0;
while (*s)
{
if (strstr(s, oldone) == s) //compare
{
strcpy(&ret[i], newone);
i += newlen;
s += oldonelen;
}
else
ret[i++] = *s++;
}
ret[i] = '\0';
return ret;
}
int main(void)
{
char mystr[100], c[10], d[10];
char fileOld[32] = "test.txt";
char fileNew[32] = "test.txt";
char word_search[80];
char word_replace[80];
FILE *fp1, *fp2;
fp1 = fopen(fileOld,"r");
fp2 = fopen(fileNew,"w");
printf("Enter the word to replace :\n");
scanf(" %s",word_search);
printf("Enter the new word:\n");
scanf(" %s",word_replace);
char *newstr = NULL;
newstr = w_replace(fileOld, word_search , word_replace);
fputs(word_replace, fp2);
fclose(fp2);
fclose(fp1);
return 0;
}
So if a test.txt contains the following sentence
This is a test
Result
Enter the word to replace :
This
Enter the new word:
That
The new updated test.txt file will only be
That
instead of
That is a test
Needed values (using the var names you gave above):
#include <fcntl.h>
int file_descriptor;
int size_of_text = <whatever you want here>;
char *file_name = "test.txt";//or whatever
char newone[size_of_text];
char oldone[size_of_text];
To read from a file:
file_descriptor = open(file_name,O_RDONLY);//O_RDONLY opens for read only
read(file_descriptor,oldone,sizeof(oldone));//reads file into oldone
close(file_descriptor);//closes so you don't accidentally read or write to it later, and so you can use it again
To write to a file:
file_descriptor = open(file_name,O_WRONLY | O_TRUNC);//O_WRONLY opens for writing only, O_TRUNC will truncate the file if it exists
write(file_descriptor,newone,sizeof(newone);//writes newone to file
close(file_descriptor);
For more information on read(),write(),open(),close():
http://www.gdsw.at/languages/c/programming-bbrown/c_075.htm

Resources