I try to use passing function as argument but I'm stuck. I have two questions:
First, I try to call uppercase and open .txt in tfm Second, How can I read characters from in.txt as string and assign to char content[] ?
#include <stdio.h>
void tfm( char str_filename[], void(*pf_convertion)( char content[]));
void uppercase(char content[]); //converts all letters to uppercase
int main(){
puts("-------------------------------");
printf("tfm:\n");
tfm("in.txt", uppercase);
puts("-------------------------------");
return 0;
}
void tfm( char str_filename[], void(*pf_convertion)( char content[])){
FILE *fptr_in;
if((fptr_in=fopen(content,"r"))==NULL){
printf("Error reading file\n");
}
else{
(*pf_convertion)(str_filename);
}
}
void uppercase(char content[]){
char ch;
int st;
for(st=fscanf(fptr_in,"%c",&ch);
st==1;
st=fscanf(fptr_in,"%c",&ch)){
if('a'<=ch && ch<='z'){
ch-=32;
printf("%c",ch);
}
else
printf("%c",ch);
}
}
Related
I get the above error in CppCheck but I can't see what's wrong.I guess the error is the reason my code doesn't find any files,even if they exist in my computer.Any help is appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 80
char *getchoice(void);
void getfile(char *filename);
int main() {
char *choice;
choice=getchoice();
getfile(choice);
return 0;
}
char *getchoice(void) {
char *filename;
filename=malloc(SIZE);
printf("Enter the name of the text file: ");
scanf("%30s",filename);
return filename;
}
void getfile(char *filename) {
FILE *fp;
fp=fopen(filename,"r");
if (fp==NULL){
printf("The entered file does not exist.");
printf("\n");
}
else{
printf("The file exists.");
}
fclose(fp);
return;
}
Here is a list of things to do, in order to clean up this program:
Handle the event that malloc fails, so that scanf and getfile are not passed NULL.
Check that scanf successfully performed the expected number of conversions, to ensure filename contains valid data.
Use perror to give more accurate information about why malloc or fopen failed.
Avoid passing NULL to fclose, in the event that fopen failed.
free memory allocated by malloc (Unlike fclose, free may be safely passed NULL).
#include <stdio.h>
#include <stdlib.h>
char *getchoice(void);
void getfile(char *filename);
int main(void) {
char *choice = getchoice();
if (choice)
getfile(choice);
free(choice);
}
char *getchoice(void) {
char *filename = malloc(80);
if (filename) {
printf("Enter the name of the text file: ");
if (1 != scanf("%79s", filename)) {
free(filename);
return NULL;
}
} else {
perror("malloc");
}
return filename;
}
void getfile(char *filename) {
FILE *fp = fopen(filename, "r");
if (fp) {
puts("File opened.");
fclose(fp);
} else {
perror("fopen");
}
}
I am trying to write a code which will read a file "part1.txt" and print/ write to a file named "part2.txt" only those words from "part1.txt" which begin with the char "#" , however in the current code the user can input any char and the output is words starting with that char.
So while running the code , it prompts Letter: and I input # .
But it's output is showing Segmentation fault, core dumped . Can you please explain what am I doing wrong?
#include <stdio.h>
char getNxtPntdVal(FILE *fPntr) {
char holder;
holder = fgetc(fPntr);
return holder;
}
void writeToFile(char c){
FILE *fpt = fopen("/home/xyz/part2.txt","a");
fputc(c,fpt);
fclose(fpt);
}
int main() {
FILE *filePtr;
char arrChar[50000];
char name[30];
char letter;
char ch;
char ch2;
int charNum=0;
filePtr = fopen("/home/xyz/part1.txt","r");
printf("Letter:");
letter=getchar();
while((ch=fgetc(filePtr))!=EOF){
if(ch==letter && charNum ==0) {
ch2 = ch;
while (ch2 != '\n') {
printf("%c", ch2);
writeToFile(ch2);
ch2 = getNxtPntdVal(filePtr);
}
charNum=charNum+1;
printf("\n");
writeToFile('\n');
} else if(ch=='\n') {
charNum=0;
}else{
charNum=charNum+1;
}
}
}
I need to write a function that returns every permute of a word in a given text file.
For some reason the output is wrong and I don't really understand why.
However, if instead of writing a function that should check a presnce of a letter (as seen below the function chars(char,char*))
I write the needed letters for check manually
it works as intended.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 100
void permute(FILE *fp, char *perm){
int c,i,perm_size=0;
int flag,chars(char,char *);
char permute[MAX];
i=0;
while(perm[i++])
perm_size++;
flag=0;
i=0;
while(!feof(fp)){
c=fgetc(fp);
if(chars(c,perm)==0){/*a function that checks c with each one of the permutes chars*/
flag++;
permute[i++]=c;
if (flag == perm_size){/*if the permute is the word's length*/
permute[i]='\0';
printf("%s\n",permute);
flag=0;
i=0;
permute[0]='\0';
}
}
else{
flag=0;
i=0;
}
}
}
int chars(char ch, char *str){
while(*str++)
{
if(ch==*str)
return 0;
}
return 1;
}
#include "func.h"
#include <string.h>
int main(int argc,char **argv){
FILE *fp;
char *input,*perm;
char *prog=argv[0];
void permute(FILE *, char *);
if(argc==1)
{
fprintf(stderr,"%s error: no arguments\n",prog);
exit(1);
}
input=argv[1];
perm=argv[2];
if(!(fp=fopen(input,"r")))
{
fprintf(stderr,"%s error: cannot open file\n",prog);
exit(1);
}
permute(fp,perm);
fclose(fp);
return 0;
}
input:
./program text chairs
output:
nothing
As told - you should really learn debuging your programs, so I did - I incremented wrongly a value in a function chars(char , char *)
a good pointer explanation from other user
I'm tring to build a simple program where i say the dimensions of a matrix i want, and i read that size from a txt file to a 2D array.
So i have the following letters as it is, in a txt file called soup.txt
ORCA
RAIO
ATNS
I want this 3x4 matrix to be loaded to an array. This are the structs and the functions that i have:
typedef struct dicionario{
char matrix[200][200];
}*DICIONARIO;
//Function to load the matrix
void abresopa(FILE *fs, char *s,DICIONARIO sopa,int dimy,int dimx){
int i;
fs=fopen (s,"r");
for (i=0;i<dimy;i++)
fgets(sopa->matrix[i],dimx,fs);
limpabn(sopa->matrix[i]);
}
//Clears \n at the end of a string
void limpabn (char *s){
int i;
for (i=0;s[i]!='\n';i++); if (s[i]=='\n') s[i]='\0';
}
My main looks like this. I'm opening the file and printing the matrix:
int main(){
struct dicionario sopa;
DICIONARIO y=&sopa;
int dimy=3, dimx=4;
FILE *fs;
abresopa(fs,"soup.txt",y,dimy,dimx);
for (i=0;i<dimy;i++) printf("%s",y->matrix[i]);
return 0;}
I was hoping to print this:
ORCARAIOATNS
But i got this instead
ORCA
RAI
What am i doing wrong?
Regards
for (i=0;i<dimy;i++)
fgets(sopa->matrix[i],dimx,fs);//<-- dimx is small size for read (XXXX\n\0)
limpabn(sopa->matrix[i]);//<- outside for-loop
shoud be
for (i=0;i<dimy;i++){
fgets(sopa->matrix[i],dimx+2,fs);
limpabn(sopa->matrix[i]);
}
fgets is used like this:
char line[256];
fgets(line, sizeof line, fp);
char *p = strchr(line, '\n');
if (p) *p = '\0';
This is a working instance. Note that array widths are just as an example. It's not very difficult to load the result a matrix.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void strip(char *s)
{
char *p2 = s;
while (*s != '\0')
{
if (*s != '\n')
{
*p2++ = *s++;
}
else
{
++s;
}
}
*p2 = '\0';
}
int main()
{
char mx[1024];
char line[200];
FILE *f = fopen("file.txt", "r");
int i = 0;
while (fgets(line, 200, f))
{
strip(line);
if (i == 0)
{
strcpy(mx, line);
}
else
{
strcat(mx, line);
}
i++;
}
printf("%s\n", mx);
return 0;
}
I really need to know how to fix this.
I have a file that is read and I store the strings from the file into an array that is passed as an argument, but I can't figure out how to make it work.
When I do print the content of the array it says null.
So how do I pass a multi-dimensional array of strings to readfiles() and make it save the strings in the array passed as parameter, each string in one position?
Thanks for the help.
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <strings.h>
#define max_chars_string 10000
#define n_strings 100
int main(int argc, char **argv)
{
char *filename;
char strings_hashes[n_strings][max_chars_string];
char * pointer_string = &strings_hashes[0][0];
int n_lines;
int i = 0;
filename = (char*)malloc(strlen(argv[1])*sizeof(char));
if(argc !=3){
fprintf(stderr, "Usage : %s [text_file] [cores]",argv[0]);
exit(0);
}
strcpy(filename,argv[1]);
read_lines(filename,pointer_string);
for(i = 0; i<n_lines;i++){
printf("%s \n",strings_hashes[i][max_chars_string]);
}
return 0;
}
void read_lines(char * filename, char *pointer){
FILE *fp;
char str[max_chars_string];
int i =0;
if((fp = fopen(filename, "r"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
while(!feof(fp)) {
while(fgets(str, sizeof str, fp)) {
strcpy(pointer, str);
printf("%s", str);
pointer++;
i++;
}
}
fclose(fp);
}
Change
void read_lines(char * filename, char *pointer){
to
void read_lines(char * filename, char (*pointer)[max_chars_string]){
(pointer's type needs to be "pointer to array of max_chars_string chars". When using pointers to access multidimensional arrays, the pointer type needs to know the all the dimensions except for the outermost one, so that it knows how far to skip along when incremented.)
Change
strcpy(pointer, str);
to
strcpy(*pointer, str);
Now call it as
read_lines(filename,strings_hashes);
(This is equivalent to the following, which may be clearer:)
read_lines(filename,&string_hashes[0]);
Finally, you want to print a string not an individual character, so use
printf("%s \n",strings_hashes[i]);